How can I get all items to display as columns using SQL pivot when number of items is large?

前端 未结 1 581
执念已碎
执念已碎 2021-01-27 07:49

If I have a table like so:

SalesPerson Product SalesAmount
Bob         Pickles $100.00
Sue         Oranges $50.00
Bob         Pickles $25.00
Bob         Oranges          


        
相关标签:
1条回答
  • 2021-01-27 08:44

    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)
    
    0 讨论(0)
提交回复
热议问题