-1

Please help me to transpose the below table, without creating a staging table. Tried PIVOT but failed. Any suggestions will also be helpful. Thanks!

Existing table:

TIME Value
4/8/2020 5:18 1
4/8/2020 5:22 0
4/8/2020 7:22 1
4/8/2020 7:31 0
4/9/2020 1:44 1
4/9/2020 1:50 0

Desired results:

1 0
4/8/2020 5:18 4/8/2020 5:22
4/8/2020 7:22 4/8/2020 7:31
4/9/2020 1:44 4/9/2020 1:50

2 Answers2

1

You can enumerate them and aggregate:

select max(case when value = 1 then time end) as value_1,
       max(case when value = 0 then time end) as value_0
from (select t.*,
             row_number() over (partition by value order by time) as seqnum
      from t
     ) t
group by seqnum;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Try this solution in combination ROW_NUMBER window function and PIVOT:

SELECT [0], [1]
FROM 
(
  SELECT Value, TIME, ROW_NUMBER() OVER (PARTITION BY Value ORDER BY TIME) Rb
  FROM MyTable
) AS SourceTable
PIVOT
(
  MAX(TIME)
  FOR Value IN ([0], [1])
) AS PivotTable
Emin Mesic
  • 1,681
  • 2
  • 8
  • 18