Splitting/Pivot Data from a Date Range using SQL

后端 未结 2 634
执念已碎
执念已碎 2021-01-16 18:44

Hi I have a problem with regarding on split/pivot dates

Here is my query

select Name
     , Start
     , End 
  from Employees 
 where St         


        
2条回答
  •  天命终不由人
    2021-01-16 19:02

    you need to generate all the dates. i did this here by using a cte. i then join this date range with your data and receive the sought result.

    with DateRange AS
    (
        SELECT CAST('1/27/2014' as DATEtime) DateValue
         UNION ALL
        SELECT dateadd(dd,1,DateValue)
          FROM DateRange
         WHERE dateadd(dd,1,DateValue) <= CAST('3/31/2014' as datetime)
    )
    select name
         , DateValue
      from Employees
      join DateRange
        on start <= DateValue
       and [end] >= datevalue
     order by 
           name
         , DateValue
    


    outdated after your updated question i would go about it with a simple union:

    select Name
         , Start
      from Employees 
     where Start >= '1/27/2014' 
       and End <= '1/31/2014'
     union all
    select Name
         , End
      from Employees 
     where Start >= '1/27/2014' 
       and End <= '1/31/2014'
     order by
           Name
    

提交回复
热议问题