MySQL案例与group by

时间:2015-04-10 04:57:39

标签: mysql group-by case

我有一张表(名字=费用),如下:

id  amount  date
1   -1687   2014-01-02 00:00:00.0
2   11000   2014-01-02 00:00:00.0
3   1500    2014-01-03 00:00:00.0
4   -3800   2014-01-03 00:00:00.0
5   119500  2014-01-01 00:00:00.0
6   -2999   2014-01-04 00:00:00.0
7   5972    2014-01-04 00:00:00.0
..
8   7208    2014-12-31 00:00:00.0

我能够检索收入并按月分组:

SELECT 
      SUM(amount), 
      date 
 FROM expense 
WHERE YEAR(now()) = YEAR(date) AND amount>0 
GROUP BY MONTH(date);

我可以检索费用并按月分组:

SELECT
      SUM(amount), 
      date 
 FROM expense 
WHERE YEAR(now()) = YEAR(date) AND amount<=0 
GROUP BY MONTH(date);

我想知道是否有办法合并这些查询并检索收入费用,并在单个查询中按月分组< / em>的

1 个答案:

答案 0 :(得分:3)

是的,你需要一个Case声明:

SELECT
   sum(case when amount> 0 then amount end) as income, 
   sum(case when amount<=0 then amount end) as expense, 
   date 
FROM expense 
WHERE YEAR(now()) = YEAR(date) 
GROUP BY MONTH(date);