I would like to widen a long table that has two columns to widen. I've found solutions for converting a long table to wide, but they all take one column and convert it to n columns. I would like to take two columns and convert the table to 2n columns.
I used this solution to successfully widen a table based on one column, but I'm not sure how to widen a second column.
Here is a sample data set similar to that of the linked solution:
Date Person Number1 Number2
2015-01-03 A 4 6
2015-01-04 A 2 5
2015-01-05 A 3 1
2015-01-03 B 5 3
2015-01-04 B 6 4
2015-01-05 B 7 6
I want to widen both columns "Number1" and "Number2" such that the output is:
Date A1 B1 A2 B2
2015-01-03 4 5 6 3
2015-01-04 2 6 5 4
2015-01-05 3 7 1 6
The solution then, based on the answer by dcieslak for widening the one column, would be:
select Date,
isNull([A], 0) as A1,
isNull([B], 0) as B1
from
( select Date, Person, Number1, Number2
from tbl ) AS SourceTable
PIVOT
( max(Number1) for Person in ( [A], [B]) ) AS PivotTable;
But how about for the second? I tried adding a second line in PIVOT
but that didn't work. I guess I could split the table into two parts and join the resulting wide tables but that seems like a bad idea because it would create such long code.