我有一个问题。如果给我一张带有正数和负数的表格,并且我想分别查找所有正数的总数和所有负数的总数并将其显示在一行中。我能够提出一种解决方案(如下)。我想检查一下使用Select和CASE语句是否有更好的解决方案
struct S {
int a;
int b;
friend ostream& operator<<(ostream& _os, const S& _s) {
_os << _s.a << ' ' << _s.b << endl;
return _os;
}
};
我的解决方案:
id amount
1 100
2 -10
3 50
4 -80
5 20
6 -20
positive negative
170 -110
答案 0 :(得分:3)
使用条件聚合:https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=e2fa9cc6aee27cc501c9cda98bc2cf2d
SELECT
SUM(CASE WHEN amount > 0 THEN amount END) AS positive,
SUM(CASE WHEN amount < 0 THEN amount END) AS negative
FROM #temp;
输出:
positive negetive
170 -110
答案 1 :(得分:0)
您还可以使用sign()
来确定它是正数还是负数
select sum(case when sign(amount) = 1 then amount end),
sum(case when sign(amount) = -1 then amount end)
from #temp
答案 2 :(得分:0)
这将起作用:
1)对于SQL Server
SELECT
SUM(IIF(amount > 0, amount, 0)) positive,
SUM(IIF(amount < 0, amount, 0)) negative
FROM TABLENAME;
2)对于SQL Server和MySQL
SELECT
SUM(CASE WHEN amount > 0 THEN amount END) positive,
SUM(CASE WHEN amount < 0 THEN amount END) negative
FROM TABLENAME;