Crosstab queries using PIVOT in SQL Server 2005
With SQL Server 2005 a lot of new features have been introduced. One of these new features is PIVOT. What this allows you to do is to turn query results on their side, so instead of having results listed down like the listing below, you have results listed across.
SalesPerson | Product | SalesAmount |
Bob | Pickles | $100.00 |
Sue | Oranges | $50.00 |
Bob | Pickles | $25.00 |
Bob | Oranges | $300.00 |
Sue | Oranges | $500.00 |
With a straight query the query results would be listed down, but the ideal solution would be to list the Products across the top for each SalesPerson, such as the following:
SalesPerson | Oranges | Pickles |
Bob | $300.00 | $125.00 |
Sue | $550.00 |
SELECT SalesPerson, [Oranges] AS Oranges, [Pickles] AS Pickles FROM (SELECT SalesPerson, Product, SalesAmount FROM ProductSales ) ps PIVOT ( SUM (SalesAmount) FOR Product IN ( [Oranges], [Pickles]) ) AS pvt |
Comments
Post a Comment