Wednesday, March 7, 2012

Pivoting a results table MSSQL

I have a query in which I would like to pivot the results

I presently have my results displaying something like this.

OrderNumber Product OrderQuantity
----- ----- -------
0608 Prod1 3
0608 Prod2 12
0608 Prod3 2

What I am after is for the results to display something like this.

OrderNumber Prod1 Prod2 Prod3
----- --- --- ---
0608 3 12 2

This is using SQL Server ver 8.0


SELECT OrderNumber,SUM(CASE WHEN Product='Prod1' THEN OrderQuantity ELSE 0 END) AS Prod1,SUM(CASE WHEN Product='Prod2' THEN OrderQuantity ELSE 0 END) AS Prod2,SUM(CASE WHEN Product='Prod3' THEN OrderQuantity ELSE 0 END) AS Prod3

FROM MyTable

GROUP BY OrderNumber

|||

Thank you, that worked perfectly!

No comments:

Post a Comment