gpt4 book ai didi

sql - 两列总计不起作用

转载 作者:行者123 更新时间:2023-12-03 18:31:28 25 4
gpt4 key购买 nike

我想从慈善机构为0的金额减去慈善机构为1的金额的总和中得出总数。

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


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

最佳答案

将所有值视为正值:

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版本的类似转换)

关于sql - 两列总计不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6085870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com