SQL语句与Group By的总和

时间:2015-05-10 22:13:00

标签: sql sql-server

我有一个具有以下结构的表(它不能更改)与复合主键

Key1 (composite primary key)
Key2 (composite primary key)
Key3 (composite primary key)
Code (also part of Primary Key)
Amount
Active

用户为每个Key1,Key2,Key3,Code和金额输入代码。用户进行输入有3个代码。我可以轻松地将它们组合在一起,以显示每个代码,key1,key2和key3的数量总和。

SELECT     SUM(Amount) AS sum
FROM         Table
GROUP BY Key1, Key2, Key3, Code

但是,我必须编写一个SQL来显示这样的结果

Key1 Key2 Key3 SumoofAmountsfCode1 SumoofAmountsfCode2 SumoofAmountsfCode3

1 个答案:

答案 0 :(得分:3)

至少有两种方法:

SELECT 
   Key1, 
   Key2, 
   Key3, 
   sum(case when code = 1 then Amount else 0 end) SumoofAmountsfCode1,
   sum(case when code = 2 then Amount else 0 end) SumoofAmountsfCode2,
   sum(case when code = 3 then Amount else 0 end) SumoofAmountsfCode3
from Table
group by Key1, Key2, Key3

或使用PIVOT

SELECT 
   Key1, 
   Key2, 
   Key3, 
   IsNull([1],0) SumoofAmountsfCode1,
   IsNull([2],0) SumoofAmountsfCode2,
   IsNull([3],0) SumoofAmountsfCode3
from Table A
pivot (sum(amount) for code in ([1],[2],[3])) B
相关问题