I am trying to write a query to transpose rows to columns. The attached image has a sample table which I want to transpose and expected output.
Any input is appreciated.
I am trying to write a query to transpose rows to columns. The attached image has a sample table which I want to transpose and expected output.
Any input is appreciated.
Option 1. Conditional aggregation
select labid, subjectid,
max(case when timepoint='T0' then val1 end) T0_val1,
max(case when timepoint='T0' then val2 end) T0_val2,
max(case when timepoint='T1' then val1 end) T1_val1,
max(case when timepoint='T1' then val2 end) T1_val2
from input
group by labid, subjectid;
Option 2. Unpivot/Pivot
select * from
(
select labid, subjectid, timepoint+'_'+col as timepoint_col, val
from
(select labid, subjectid, timepoint, val1, val2
from input) as src
unpivot
(
val for col in (val1, val2)
) as unpiv) as x
pivot
(
max(val)
for timepoint_col in ([T0_val1],[T0_val2],[T1_val1],[T1_val2])
) as piv1