Mysql的。从SUM(c.Amount)中扣除SUM(d.Amount)并在其他列中分组(取决于)值

时间:2013-07-24 08:42:17

标签: mysql

这是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

的所有Amounts求和

2)对CreditAccount 5610 TransactionPartnerNamename oneCreditAccount

的所有DebitAccount求和

3)从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总和

试过这段代码

151

但在帐号SUM(Amount)的结果中获取值DebitAccount。这意味着CreditAccountSELECT 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 的{​​{1}}。

试图思考如何修改。

尝试过这样的事情

{{1}}

但得到空白页....

请建议需要纠正的内容

1 个答案:

答案 0 :(得分:1)

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

试试这个


编辑:删除了内部查询