我有一张表格:
id year type amount
1 2015 in 10
2 2015 out 5
3 2016 in 20
4 2016 out 1
...
以下查询将为我提供'中&type ='的类型总和。按年份分组:
SELECT year, sum(amount)
FROM table
WHERE type = in
GROUP BY year
我将如何获得以下结果?
year sum(in) sum(out) "in-out"
2015 10 5 5
2016 20 1 19
总和(in)是'金额的总和'其中type =' in'。
答案 0 :(得分:4)
使用CASE语句处理type
。
SELECT year,
SUM(CASE WHEN type = 'in' THEN amount ELSE 0 END) AS sum_in,
SUM(CASE WHEN type = 'out' THEN amount ELSE 0 END) AS sum_out,
SUM(CASE WHEN type = 'in' THEN amount ELSE -amount END) AS in_out
FROM table
GROUP BY year;