If I have a table like so:
SalesPerson Product SalesAmount
Bob Pickles $100.00
Sue Oranges $50.00
Bob Pickles $25.00
Bob Oranges
see,i do not know you exact table design. I am just trying to give you rough idea here,And this is just main part of whole query .
Declare @item varchar(500)
Declare @Sql varchar(max)
create table t (SalesPerson varchar(50), Product varchar(50), SalesAmount float)
insert into t values
('Bob','Pickles', 100.00)
,('Sue','Oranges', 50.00)
,('Bob','Pickles', 25.00)
,('Bob','Oranges', 300.00)
,('Sue','Oranges', 500.00)
;With CTE as
(
Select distinct product from t
)
select
@item=stuff((select ','+ '['+ product + ']' from cte for xml path('')),1,1,'')
from CTE A
print @item --debug
set @sql=' SELECT SalesPerson, '+@item+'
FROM
(SELECT SalesPerson, Product, SalesAmount
FROM t ) ps
PIVOT
(
SUM (SalesAmount)
FOR Product IN
( '+@item+')
) AS pvt '
print @sql --debug
exec (@sql)