需要从信用卡和借记卡帐号相同的借方总计中减去信用总额。如果某个值仅存在于借方帐号,则无需减去任何内容,只需获取该值即可。
一个名为18_7_ChartOfAccounts的表如下所示:
ID | AccountNumber
-------------
1 | 2310
2 | 2380
另一个名为2_1_journal的表格如下:
ID | Amount | DebitAccount | CreditAccount
-------------------------------------------
1 | 25.00 | 2310 | 2380
2 | 200.00 | 2310 | 2380
3 | 4.00 | 2380 | 2310
4 | 200.00 | 2380 | 2310
5 | 50.00 | 2380 | 2620
根据建议创建的查询,该查询汇总Amount
列中DebitAccount
中的值相同的所有值。
查询执行以下操作:SUM(Amount)
FROM table 2_1_journal
表DebitAccount
中的2_1_journal
与表AccountNumber
中的18_7_ChartOfAccounts
相同< / p>
$query_debit_beginning = "SELECT SUM(j.Amount), j.DebitAccount FROM 18_7_ChartOfAccounts AS c LEFT JOIN 2_1_journal AS j ON (c.AccountNumber = j.DebitAccount) group by j.DebitAccount";
不明白如何减去其他的总和。
需要像这样输出
帐号为2310,值为21.00(25 + 200-4-200)
帐号为2380,值为29.00(4 + 200 + 50-25-200)
帐号为2620,值为-50.00(0(DebitAccount营业额) - 50(CreditAccount营业额))
查询应如下:
(SUM(Amount)
FROM table 2_1_journal
表DebitAccount
中的2_1_journal
与表AccountNumber
中的18_7_ChartOfAccounts
相同
然后
SUM(Amount)
FROM table 2_1_journal
表CreditAccount
中的2_1_journal
与表AccountNumber
中的18_7_ChartOfAccounts
相同
然后
如果DebitAccount
等于CreditAccount
,则从SUM(Amount)
CreditAccount减去SUM(Amount)
DebitAccount
不知道如何创建此类查询。请,建议。
根据建议试图为select添加条件。 这是修改。代码是否正确?尝试并且似乎在必要时起作用
SELECT
a.AccountNumber,
IFNULL( d.Amount, 0 ) - IFNULL( c.Amount, 0 ) AS Amount
FROM 18_7_ChartOfAccounts AS a
LEFT JOIN (
SELECT
DebitAccount, RecordYear,
SUM( Amount ) AS Amount
FROM 2_1_journal WHERE RecordYear = 2013
GROUP BY DebitAccount
) d ON (a.AccountNumber = d.DebitAccount)
LEFT JOIN (
SELECT
CreditAccount, RecordYear,
SUM( Amount ) AS Amount
FROM 2_1_journal WHERE RecordYear = 2013
GROUP BY CreditAccount
) c ON (a.AccountNumber = c.CreditAccount)
答案 0 :(得分:6)
SELECT
a.AccountNumber,
IFNULL( d.Amount, 0 ) - IFNULL( c.Amount, 0 ) AS Amount
FROM 18_7_ChartOfAccounts AS a
LEFT JOIN (
SELECT
DebitAccount,
SUM( Amount ) AS Amount
FROM 2_1_journal
GROUP BY DebitAccount
) d ON a.AccountNumber = d.DebitAccount
LEFT JOIN (
SELECT
CreditAccount,
SUM( Amount ) AS Amount
FROM 2_1_journal
GROUP BY CreditAccount
) c ON a.AccountNumber = d.CreditAccount
答案 1 :(得分:2)
这样的事情应该做(未经测试)
SELECT a.ID, a.AccountNumber, IFNULL( CreditAmount, 0 ) - IFNULL( DebitAmount, 0 )
FROM 18_7_ChartOfAccounts a
LEFT OUTER JOIN (SELECT DebitAccount AS AccountNo, SUM(Amount) AS DebitAmount FROM 2_1_journal GROUP BY DebitAccount) b ON a.AccountNumber = b.AccountNo
LEFT OUTER JOIN (SELECT CreditAccount AS AccountNo, SUM(Amount) AS CreditAmount FROM 2_1_journal GROUP BY CreditAccount) c ON a.AccountNumber = c.AccountNo
LEFT OUTER JOIN 2_1_journal c ON a.AccountNumber = c.CreditAccount
GROUP BY a.ID, a.AccountNumber