If I have a table like so:
SalesPerson Product SalesAmount
Bob Pickles $100.00
Sue Oranges $50.00
Bob Pickles $25.00
Bob Oranges $300.00
Sue Oranges $500.00
and I wanted to get
SalesPerson Oranges Pickles
Bob $300.00 $125.00
Sue $550.00
I would use:
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
However this would be a bit of a pain if I had a large number of products and I wanted to get the same result. I'm guessing I could use a Select statement like so:
FOR Product IN(SELECT DISTINCT(Product) FROM ProductSales
but I would still need to define the individual column headings i.e.
SELECT SalesPerson, [Oranges] AS Oranges, [Pickles] AS Pickles, [Bagels] AS Bagels, [MonsterTrucks] AS MonsterTrucks...
Is there a more efficient way of going about achieving this?