2

我有列类型(0 或 1)、数量(int)的表

我需要查询返回 2 个参数的内容:类型 = 1 的总金额和类型 = 0 的总金额

2个查询:

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

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

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

4

2 回答 2

3
SELECT SUM(amount), IF(type=0, 'income', 'expense') AS type
FROM table
GROUP BY type
于 2012-12-08T13:35:16.560 回答
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

演示

于 2012-12-08T13:36:58.217 回答