我如何在MYSQL中执行此操作?

时间:2015-02-12 21:38:46

标签: mysql

我在MySQL中有以下个人财务样本数据:

+---------------------------------------------------------------------------+
| id |    date    | amount | year | month |  description   | type | balance |
+---------------------------------------------------------------------------+
|  4 | 2015-02-03 | 563.00 | 2015 |   2   | Some text here |  out | -342.00 |
+---------------------------------------------------------------------------+
|  3 | 2015-02-01 | 102.95 | 2015 |   2   | Some text here |  in  |  221.00 |
+---------------------------------------------------------------------------+
|  2 | 2015-01-17 | 586.38 | 2015 |   1   | Some text here |  out |  184.96 |
+---------------------------------------------------------------------------+
|  1 | 2015-01-09 | 421.15 | 2015 |   1   | Some text here |  in  |  771.34 |
+---------------------------------------------------------------------------+

我想要的是某种视图/查询。选定年份中每个月的单行,其中SUM(金额)与每种类型分开,有点像这样:

+-------------------------------------+
| year | month | total_in | total_out | 
+-------------------------------------+
| 2015 |   2   |  xxx.xx  |  xxx.xx   |
+-------------------------------------+
| 2015 |   1   |  xxx.xx  |  xxx.xx   |
+-------------------------------------+

使用以下查询

SELECT year, month, type, SUM(amount) as total_amount
FROM table
WHERE year = 2015
GROUP BY month, type
ORDER BY month
DESC

我只是这样:

+------------------------------------+
| year | month | type | total_amount |
+------------------------------------+
| 2015 |   2   |  in  |    xxx.xx    |
+------------------------------------+
| 2015 |   2   |  out |    xxx.xx    |
+------------------------------------+
| 2015 |   1   |  in  |    xxx.xx    |
+------------------------------------+
| 2015 |   1   |  out |    xxx.xx    |
+------------------------------------+

我在这里缺少什么?

谢谢!

1 个答案:

答案 0 :(得分:4)

你很亲密。您需要条件聚合:

SELECT year, month, 
       SUM(case when type = 'in' then amount else 0 end) as total_in,
       SUM(case when type = 'out' then amount else 0 end) as total_out
FROM table
WHERE year = 2015
GROUP BY year, month
ORDER BY year desc, month DESC;