pivot - How to transpose rows into columns in SQL Server? -


i have been working on how transpose or pivot table after working many hours still stuck on this, can please me?

my table looks this:

create table table1 (      `time` datetime,       `in` int,       `out` int );  insert table1 (`time`, `in`, `out`) values ('2017-04-05 15:53:00', 40, '35'),        ('2017-04-05 15:24:00', 40, '35'),        ('2017-04-05 15:23:00', 40, '35'),        ('2017-04-05 14:22:00', 42, '40'),        ('2017-04-05 14:21:00', 42, '40'),        ('2017-04-05 14:20:00', 42, '40'),        ('2017-04-05 13:19:00', 33, '30'),        ('2017-04-05 13:18:00', 33, '30'),        ('2017-04-05 13:17:00', 33, '30'),        ('2017-04-05 13:16:00', 33, '30'),        ('2017-04-05 13:15:00', 33, '30'),        ('2017-04-05 12:14:00', 29, '25'),        ('2017-04-05 12:13:00', 29, '25'),        ('2017-04-05 12:12:00', 29, '25'),        ('2017-04-05 12:11:00', 29, '25'),        ('2017-04-05 11:14:00', 35, '33'),        ('2017-04-05 11:13:00', 35, '33'),        ('2017-04-05 11:12:00', 35, '33'),        ('2017-04-05 11:11:00', 35, '33'); 

i want output similar this

enter image description here

the value in 'in' column same particular hour entered several time, need 1 value in table same value in 'out' column

the accum accumulated sum each hour, make optional if possible.

i doing first part transpose 2 columns query

select      'in' a, [2017-04-05 15:53:00], [2017-04-05 14:22:00],,,,      (select           [time], [in], [out]                 table1) sourcetable pivot     (max([in])         [time] in ([2017-04-05 15:53:00], [2017-04-05 14:22:00],,,,)) pivottable; 

you can try this,

select [type], [11], [12], [13], [14], [15] (   select [time], [type], value   (     select t2.*, sum([out]) on (order [time]) accum     (select distinct datepart(hour, time) [time], [in], [out] table1) t2     )   unpivot   (     value [type] in ([in],[out],[accum])   ) unpiv ) src pivot (   sum(value)   [time] in ([11], [12], [13], [14], [15]) ) piv 

get more details here make dynamic, simple way transpose columns , rows in sql? accumulate summarized column


Comments