gpt4 book ai didi

mysql。从 SUM(c.Amount) 中减去 SUM(d.Amount),并按(取决于)其他列中的值进行分组

转载 作者:行者123 更新时间:2023-11-29 13:43:02 25 4
gpt4 key购买 nike

这是 MySQL 表

Amount | DebitAccount | CreditAccount | TransactionPartnerName
--------------------------------------------------------------
1 | 5610 | 5720 | name one
150 | 7210 | 5610 | name one

需要得到这样的东西

name one result for account 5610 = 149.
((`CreditAccount` for `5610`) - (`DebitAccount` for `5610`)) = 149

换句话说:

1) 总和Amounts哪里DebitAccount5610TransactionPartnerNamename one

2) 总和 Amounts哪里CreditAccount5610TransactionPartnerNamename one

3) 来自CreditAccount总和扣除DebitAccount总和

尝试了这段代码

SELECT TransactionPartnerName, SUM(Amount) 
FROM ( SELECT * FROM 2_1_journal) DATA
WHERE (CAST(DebitAccount AS UNSIGNED) IN (?) OR CAST(CreditAccount AS UNSIGNED) IN (?))
GROUP BY TransactionPartnerName

但帐户的结果为5610获取值(value)151 。这意味着SUM(Amount)DebitAccountCreditAccount .

尝试思考如何修改。

尝试过类似的事情

SELECT TransactionPartnerName, 
IFNULL( d.Amount, 0 ) - IFNULL( c.Amount, 0 ) AS Amount

FROM

(
SELECT DebitAccount,

SUM( Amount ) AS Amount FROM
( SELECT * FROM 2_1_journal) DATA

GROUP BY DebitAccount
) d ON (AccountNumber = d.DebitAccount)

(
SELECT CreditAccount,
SUM( Amount ) AS Amount FROM
( SELECT * FROM 2_1_journal) DATA
GROUP BY CreditAccount
) c ON (AccountNumber = c.CreditAccount)

GROUP BY TransactionPartnerName

但是得到空白页......

请指出需要纠正的地方

最佳答案

SELECT TransactionPartnerName, SUM(if(CAST(DebitAccount AS UNSIGNED) IN (?), -Amount, Amount)) 
FROM 2_1_journal DATA
WHERE (CAST(DebitAccount AS UNSIGNED) IN (?) OR CAST(CreditAccount AS UNSIGNED) IN (?))
GROUP BY TransactionPartnerName

试试这个


编辑:删除内部查询

关于mysql。从 SUM(c.Amount) 中减去 SUM(d.Amount),并按(取决于)其他列中的值进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17829089/

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