Search code examples
sqloracleanalytics

How to get grouped sums listed on the same row?


I have below mock up data,

itemNum    itemName       type        count  
-------------------------------------------------  
1111       A001           1           2  
1111       A001           1           4  
1111       A001           3           2  
1111       A001           3           5  
1111       A001           3           3  
1111       A001           3           6  
2222       A002           1           3  
2222       A002           1           5  
2222       A002           2           4  
2222       A002           2           7  
2222       A002           3           8  
2222       A002           3           9  

i need the sums of one item per type listed in the same row,(there will be only 3 types, so will have three columns sum1, sum2, sum3.) The result i need is ,

itemNum    itemName      sum1      sum2      sum3  
--------------------------------------------------  
1111        A001         6          7         9
2222        A002         8          11        17

How do i write the oracle sql script ? Thanks.


Solution

  • You can use pivot as following:

    Select * from
    (Select * from your_table)
    Pivot
    (
    Sum(count) 
    for type in (1 as sum_1, 2 as sum_2, 3 as sum_3)
    )
    

    Cheers!!