第一个表(名为18_8_ChartOfAccounts
),帐号如此
AccountNumber | VatReturnRowNumberForDebitTurnover
--------------------------------------------------
1 | not_blank
2 |
3 | not_blank
第二个表(名为2_1_journal
),如下所示
Amount | DebitAccount
----------------------
5 | 1
80 | 2
3 | 3
4 | 1
20 | 3
尝试获取以下内容:如果VatReturnRowNumberForDebitTurnover
不为空/非空,请Amount
求DebitAccount
与(等于)AccountNumber
相同。
或者想得到这样的输出:
Account number | Total
---------------------------
1 | 9 (5+4)
3 | 23 (20+3)
不需要回复帐户2
的总计,因为帐户2
VatReturnRowNumberForDebitTurnover
为空/空
此mysql查询从第一个表(AccountNumber
)中选择所有 18_8_ChartOfAccounts
SELECT a.AccountNumber, IFNULL( d.Amount, 0 ) AS Amount
FROM 18_8_ChartOfAccounts AS a
LEFT JOIN ( SELECT DebitAccount, SUM( Amount ) AS Amount
FROM ( SELECT * FROM 2_1_journal) DATA
GROUP BY DebitAccount )
d ON (a.AccountNumber = d.DebitAccount)
但只需要选择AccountNumber
,其中VatReturnRowNumberForDebitTurnover
不为空/空
尝试修改mysql查询
SELECT a.AccountNumber, IFNULL( d.Amount, 0 ) AS Amount
FROM 18_8_ChartOfAccounts AS a
WHERE VatReturnRowNumberForDebitTurnover <> ''
LEFT JOIN ( SELECT DebitAccount, SUM( Amount ) AS Amount
FROM ( SELECT * FROM 2_1_journal) DATA
GROUP BY DebitAccount )
d ON (a.AccountNumber = d.DebitAccount)
获取Syntax error or access violation: ... near 'LEFT JOIN ( SELECT DebitAccount ....
然后更改了FROM 18_8_ChartOfAccounts AS a WHERE VatReturnRowNumberForDebitTurnover <> ''
到FROM 18_8_ChartOfAccounts WHERE VatReturnRowNumberForDebitTurnover <> '' AS a
并收到类似的错误。
然后改为这样的代码:
SELECT a.AccountNumber, IFNULL( d.Amount, 0 ) AS Amount
FROM 18_8_ChartOfAccounts AS a
LEFT JOIN ( SELECT DebitAccount, SUM( Amount ) AS Amount
FROM ( SELECT * FROM 2_1_journal) DATA
WHERE a.VatReturnRowNumberForDebitTurnover <> ""
GROUP BY DebitAccount )
d ON (a.AccountNumber = d.DebitAccount)
并获取Unknown column 'a.VatReturnRowNumberForDebitTurnover'
在表2_1_journal
中没有这样的专栏。想要使用与a.VatReturnRowNumberForDebitTurnover
相同的方式a.AccountNumber
(两个列仅位于18_8_ChartOfAccounts
。a.AccountNumber
有效,a.VatReturnRowNumberForDebitTurnover
无效。
请建议需要修改的内容
答案 0 :(得分:3)
这应该有用;
SELECT AccountNumber,
CONCAT(SUM(Amount), ' (', GROUP_CONCAT(Amount SEPARATOR '+'), ')') Total
FROM 18_8_ChartOfAccounts
LEFT JOIN 2_1_journal
ON AccountNumber = DebitAccount
WHERE VatReturnRowNumberForDebitTurnover IS NOT NULL
GROUP BY AccountNumber
当然,如果总结细节只是一个例子,你可以跳过GROUP_CONCAT()
部分,然后使用......
SELECT AccountNumber, COALESCE(SUM(Amount), 0) Total
...
答案 1 :(得分:2)
只需使用此查询:
SELECT a.AccountNumber, SUM( b.Amount ) AS Amount
FROM 18_8_ChartOfAccounts AS a
LEFT JOIN 2_1_journal AS b ON a.AccountNumber = b.DebitAccount
WHERE a.VatReturnRowNumberForDebitTurnover IS NOT NULL
GROUP BY b.DebitAccount;
答案 2 :(得分:1)
select
ca.AccountNumber,
sum(j.Amount)
from
18_8_ChartOfAccounts ca
left join 2_1_journal j on ca.AccountNumber = j.DebitAccount
where
ca.VatReturnRowNumberForDebitTurnover is not null
group by ca.AccountNumber
看到它在sqlfiddle中正常工作。