在1个查询中:2个结果,使用2个条件

时间:2012-12-08 13:33:16

标签: mysql sql

我的表有列类型(0或1),金额(int)

我需要查询什么返回2个参数:type = 1的总和金额和type = 0的总金额

2个查询:

SELECT SUM(amount) AS income FROM table WHERE type = 0;

SELECT SUM(amount) AS expense FROM table WHERE type = 1;

但我可以仅使用1个查询返回这些参数吗?

2 个答案:

答案 0 :(得分:3)

SELECT SUM(amount), IF(type=0, 'income', 'expense') AS type
FROM table
GROUP BY type

答案 1 :(得分:1)

SELECT sum(case when type = 0 
           then amount
           else 0 
           end) AS income,
       sum(case when type = 1 
           then amount
           else 0
           end) AS expense
FROM table

Demo