我有一个简单的SQL表,格式如下:
date | value
============
2010-01-01 | -54
2010-01-02 | 134
2010-01-03 | 73
通过以下两个SQL查询,我可以选择值的总和,并区分正值之和和负值之和。
SELECT YEAR(date), SUM(value) FROM table WHERE value > 0 GROUP BY YEAR(date)
SELECT YEAR(date), SUM(value) FROM table WHERE value < 0 GROUP BY YEAR(date)
有没有办法在单个SQL查询中执行此操作?
提前致谢!
答案 0 :(得分:4)
未经过测试(不知道案例是否可以放在SUM指令中),但CASE指令可能有所帮助:
SELECT
YEAR(date),
SUM(CASE WHEN value > 0 THEN value ELSE 0 END) as positives_sum,
SUM(CASE WHEN value < 0 THEN value ELSE 0 END) as negatives_sum
FROM
table
GROUP BY
YEAR(date)
答案 1 :(得分:2)
许多数据库都有一个SIGN()函数
SELECT YEAR(date),
SUM(value)
FROM table
GROUP BY YEAR(date),
SIGN(value)