我有一个充满交易的数据库表。交易包含人们返回项目的负数。我想将所有金额字段相加,同时从总计中减去返回的负值。我怎么能这样做并输出呢? 目前我能做的最好的就是:
SELECT SUM(amount)
FROM outputaddition
GROUP by SIGN(amount);
但这只会在同一栏中放置正面和负面。
答案 0 :(得分:12)
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
答案 1 :(得分:0)
我担心你的答案含糊不清;我们不确定你在问什么。
最简单的说,如果“减去负值”意味着你只想忽略负面回报:
选择总和(金额) 其中数量> 0;
答案 2 :(得分:0)
试试这个,
SELECT SUM(amount) as ActualTotal
,Sum(Case When amount > 0 then amount else 0 end) totalOfPositiveOnly
FROM outputaddition