我正在使用翻译
写作表1
id number type
1 6 111
1 5 111
1 6 113
2 3 112
2 6 111
我需要按"类型"的值对组进行求和。和" id" 我希望看到的结果
结果表
id type111 type112 typ113
1 11 0 6
2 6 3 0
答案 0 :(得分:0)
尝试将SUM与CASE一起使用:
SELECT ID,
SUM(CASE WHEN type = 111 THEN number END) AS type111,
SUM(CASE WHEN type = 112 THEN number END) AS type112,
SUM(CASE WHEN type = 113 THEN number END) AS typE113,
FROM TABLE1
GROUP BY ID
答案 1 :(得分:0)
另一种使用pivoting的方式:
SELECT id,
ISNULL([111],0) as Type111,
ISNULL([112],0) as Type112,
ISNULL([113],0) as Type113
FROM (
SELECT id,
number,
[type]
FROM Table1
) AS SourceTable
PIVOT (SUM(number) FOR [type] IN ([111], [112], [113])
) AS PivotTable;
输出:
id Type111 Type112 Type113
----------- ----------- ----------- -----------
1 11 0 6
2 6 3 0
(2 rows affected)
如果各种类型都很高 - 使用动态SQL来构建和执行查询。