convert date timeline in rows to columnar format in sql server -
my data :
sku startdatetime enddatetime es311335 6/30/2013 5/24/2015 es311355 6/30/2013 6/28/2015 es311470 6/30/2013 12/14/2014 es311478 6/30/2013 6/28/2015 es311501 6/30/2013 6/28/2015 es311574 6/30/2013 6/28/2015 es311632 6/30/2013 6/22/2014
i want in format:
sku date es311335 6/30/2013 es311335 7/7/2013 es311335 7/14/2013 es311335 7/21/2013 es311335 7/28/2013 es311335 8/4/2013 ------ ------ es311335 24/05/2014
i have used below query not giving me correct result.
declare @interval nvarchar(10), @i datetime, @intervalmin datetime, @intervalmax datetime --- set interval day or month or year ----------------- set @interval = 'day' ------------------------------------------------------- declare @records table (startdatetime datetime ,enddatetime datetime) insert @records select startdatetime, enddatetime records declare @results table (startdate datetime ,enddate datetime) while exists(select * @records) begin select top 1 @intervalmin = startdatetime, @intervalmax = enddatetime @records set @i = @intervalmin while (@i <= @intervalmax) begin if @interval = 'day' begin insert @results select @i, case when convert(date, dateadd(day, 7, @i)) > @intervalmax @intervalmax else convert(date, dateadd(day, 7, @i)) end set @i = convert(date, dateadd(day, 7, @i)) end end delete @records startdatetime = @intervalmin , enddatetime = @intervalmax end select * @results
i mentioned in comment should use tally table. here version of tally table. keep view in system don't have store permanently , generates 10,000 rows 0 reads.
create view [dbo].[ctetally] e1(n) (select 1 (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)), e2(n) (select 1 e1 a, e1 b), --10e+2 or 100 rows e4(n) (select 1 e2 a, e2 b), --10e+4 or 10,000 rows max ctetally(n) ( select row_number() on (order (select null)) e4 ) select n ctetally
now how apply trying do? can date math incorporate tally table solution set based instead of rbar (row agonizing row) looping construct. before can solution have build data in format consumable others.
here 1 way that.
if object_id('tempdb..#something') not null drop table #something create table #something ( sku char(9) , startdatetime datetime , enddatetime datetime ) insert #something select 'es311335', '6/30/2013', '5/24/2015' union select 'es311355', '6/30/2013', '6/28/2015' union select 'es311470', '6/30/2013', '12/14/2014' union select 'es311478', '6/30/2013', '6/28/2015' union select 'es311501', '6/30/2013', '6/28/2015' union select 'es311574', '6/30/2013', '6/28/2015' union select 'es311632', '6/30/2013', '6/22/2014'
ok cool. have tally table , data work with. let's see how simple can when use our tally table.
select s.* , dateadd(week, n - 1, startdatetime) #something s join ctetally t on t.n <= datediff(week, startdatetime, enddatetime) + 1 order sku, dateadd(week, n - 1, startdatetime)
Comments
Post a Comment