我有一个充满交易的数据库表.交易包含人们返回项目的负数.我想将所有金额字段相加,同时从总计中减去返回的负值.我怎么能这样做并输出呢?
目前我能做的最好的事情是:
SELECT SUM(amount)
FROM outputaddition
GROUP by SIGN(amount);
但这只会在同一栏中放置正面和负面.
最佳答案
SELECT personId,SUM(CASE WHEN amount<0 THEN amount ELSE 0 END) as NegativeTotal,SUM(CASE WHEN amount>=0 THEN amount ELSE 0 END) as PostiveTotal
FROM outputaddition
GROUP BY personID
如果你想要单列
SELECT personId,SUM(amount) as Total
FROM outputaddition
GROUP BY personID