如何获得列在同一行的分组总和?

How to get grouped sums listed on the same row?

我有以下模拟数据,

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  

我需要在同一行中列出每种类型的一项的总和,(只有 3 种类型,因此将有三列 sum1、sum2、sum3。)我需要的结果是,

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

如何编写 oracle sql 脚本?谢谢

只使用条件聚合:

select itemnum, itemname,
       sum(case when type = 1 then count end) as sum_1,
       sum(case when type = 2 then count end) as sum_2,
       sum(case when type = 3 then count end) as sum_4
from t
group by itemnum, itemname;

您可以使用 pivot 如下:

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

干杯!!