我正在尝试查找可以帮助我执行以下操作的查询,我有一个像bellow一样的表
ID1 VALUE1 ID2 VALUE2
=========================
1 1 2 2
1 2 1 2
2 3 2 4
2 4 3 5
3 6 1 5
4 2 1 1
我正在寻找
ID VALUE1 VALUE2
=========================
1 3 8
2 7 6
3 6 5
4 2 0
基本上,在ID1中搜索并在Value1中显示sum并在ID2中搜索相同的ID并显示Value2的总和
我试过
SELECT
ID1 as ID,
SUM(VALUE1) AS VALUE1,
SUM(VALUE2) AS VALUE2
FROM TABLE
GROUP BY ID1;
但上面的查询没有显示我想要的内容。
我将它与两个ID联合起来
SELECT ID1 as ID from TABLE
UNION
SELECT ID2 from TABLE
但后来我不知道如何使用创建的列来搜索Value1和Value2
答案 0 :(得分:2)
使用union all
将四列合并为更合理的格式。然后与group by
汇总:
select id, sum(value1), sum(value2)
from ((select id1 as id, value1 as val1, 0 as val2 from t
) union all
(select id2, 0, value2 from t
)
) tt
group by id;