I’ve seen many rows-to-columns threads here but can’t find exactly what I’m looking for.
How do you convert the following table:
ID Foo Bar
1 A F
2 B G
3 C H
4 D I
5 E J
Into this:
ID 1 2 3 4 5
Foo A B C D E
Bar F G H I J
Thanks! I am using SQL Server 2005 by the way.
Here is an answer. As I alluded to in my comment, this only works in the dimensions that you’re working with are known/fixed. First, the sample data:
The output when merely selecting from
Rot1is:So, we can construct this query, so long as we know all of the cross-referencing identifiers, e.g.
Foo,Bar,1,2,3,4, and5. In most cases of wanting to do this kind of transform, you don’t know all of these values, and so SQL isn’t the way to achieve the transform – use whatever tool is consuming the original results to achieve this kind of reformatting.