总共两列不起作用

时间:2011-05-22 03:39:16

标签: sql sqlite system.data.sqlite

我希望从慈善机构为0的金额减去慈善机构为1的金额总和。

SELECT SUM(Amount) - (SELECT SUM(Amount) 
                        FROM Transactions 
                       WHERE (Charity = 1))
  FROM Transactions 
 WHERE (Charity = 0)

此查询运行但不会给我正确的结果。

3 个答案:

答案 0 :(得分:2)

将所有值视为正面:

SELECT SUM(ABS(Amount)) - (SELECT SUM(ABS(Amount)) 
                        FROM Transactions 
                       WHERE (Charity = 1))
  FROM Transactions 
 WHERE (Charity = 0)

但严重怀疑负面交易应该像积极的一样对待。如果此表中存在合法的否定交易,那么它们应该被视为否定(如在您的原始查询中)或被排除在外:

SELECT SUM(Amount) - (SELECT SUM(Amount) 
                        FROM Transactions 
                       WHERE (Charity = 1) AND Amount > 0)
  FROM Transactions 
 WHERE (Charity = 0) AND Amount > 0

不确定sqlite中有哪些可用设施。在标准SQL中,我可能会将其重写为:

SELECT
    COALESCE(SUM(CASE WHEN Charity=0 THEN Amount END),0) -
    COALESCE(SUM(CASE WHEN Charity=1 THEN Amount END),0)
FROM Transactions
WHERE
    Charity in (0,1) AND
    Amount > 0

(或ABS版本的类似转换)

答案 1 :(得分:1)

尝试这是否有帮助。

select a.sum1 - b.sum2
from
(SELECT  SUM(Amount) as sum1 FROM Transactions WHERE (Charity = 0)) A,
(SELECT  SUM(Amount) as sum2 FROM Transactions WHERE (Charity = 1)) B

答案 2 :(得分:1)

尝试下面的内容(我希望这在SQLite中有效):

SELECT (SELECT  SUM(Amount) FROM Transactions WHERE (Charity = 0)) - 
       (SELECT  SUM(Amount) FROM Transactions WHERE (Charity = 1))