两个SUM和两个GROUP BY

时间:2015-03-22 22:52:46

标签: mysql group-by sum

我有一个像这样的选择查询,它可以得到正确的结果:

SELECT SUM(value) AS "sum1" FROM table GROUP BY id1, id2

现在我希望通过这样的条件与另一个组进行第二次求和,这也得到了正确的结果:

SELECT SUM(value) AS "sum2" FROM table GROUP BY id1

但是我如何构建一个选择查询,这给了我两个总和?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

SELECT t1.sum1, t2.sum2
FROM 
(select sum(value) as sum1 from table group by id1, id2) as t1
join 
(select sum(value) as sum2 from table group by id1) as t2

但是由于您有不同的组,结果将为sum1提供重复值...不知道它是否有用。