PIVOT on Multiple Columns

前端 未结 3 597
南旧
南旧 2021-01-26 20:41

I have data like this:

Product Group     Product Level    Quatity Sold     Trend
==============================================================
Group 1                   


        
3条回答
  •  离开以前
    2021-01-26 20:58

    You can potentially do this using correlated subqueries:

    select productGroup as [Product Group]
        , (select sum(quantitySold) from myTable where productGroup = a.productGroup and productLevel = 'L1') as L1
        , (select max(trend) from myTable where productGroup = a.productGroup and productLevel = 'L1') as L1Trend
        , (select sum(quantitySold) from myTable where productGroup = a.productGroup and productLevel = 'L2') as L2
        , (select max(trend) from myTable where productGroup = a.productGroup and productLevel = 'L2') as L2Trend
        -- etc.
    from myTable a
    group by productGroup 
    order by productGroup
    

    Here's an example SqlFiddle.

    It may help you to see it this way before you use the PIVOT keyword.

    If you don't know how many productLevel values you have, you'd need a dynamic solution, however.

提交回复
热议问题