我有多张桌子,我只用3来测试。我不知道这是否是正确的方法。
AccntTbl
id accnt amount date
---------------------------------
1 xxx 10.00 1/1/2016
2 yyy 20.00 1/1/2016
3 zzz 30.00 1/1/2016
SupplyTbl
id accnt supply date
-------------------------------
1 xxx 5.00 1/10/2016
1 xxx 5.00 2/14/2016
IssuedTbl
id accnt issued date
---------------------------------
1 xxx 3.00 1/9/2016
1 xxx 2.00 2/1/2016
如果过滤到JANUARY
,结果将是这样的 id accnt amount issued balance
--------------------------------------------
1 xxx 15.00 3.00 12.00
2 yyy 20.00 0.00 20.00
3 zzz 30.00 0.00 30.00
如果是FEBRUARY
id accnt amount issued balance
---------------------------------------------
1 xxx 20.00 5.00 15.00
2 yyy 20.00 0.00 0.00
3 zzz 30.00 0.00 0.00
这是我提出的问题
SELECT accnttbl.id,
accnttbl.accnt,
Sum(accnttbl.amount)
+ Sum(SupplyTbl.supply) AS amount,
issuedtbl.issued
FROM accnttbl
LEFT JOIN (SELECT id,
Sum(supply) AS supply,
date
FROM supplytbl
GROUP BY id,
date) AS SupplyTbl
ON accnttbl.id = SupplyTbl.id
AND Month(SupplyTbl.date) BETWEEN 1 AND 2
LEFT JOIN (SELECT id. Sum(issued) AS issued,
date
FROM issuedtbl
GROUP BY id,
date)
ON accnttbl.id = issuedtbl.id
AND Month(issuedtbl.date) BETWEEN 1 AND 2
WHERE Year(accnttbl.date) = 2016
GROUP BY accnttbl.id,
accnttbl.accnt
我有点搞砸......很高兴得到任何帮助:)
结果就像这样...... 1月份
id accnt amount issued
1 xxx 30.00 10.00
2 yyy 20.00 0.00
和在FEBRUARY
1 xxx 60.00 20.00
2 yyy 20.00 0.00
用我给出的值......只是..它自己加倍了......结果是错的......为什么?
答案 0 :(得分:0)
尝试如下:
SELECT AccntTbl.id, AccntTbl.accnt
, SUM(AccntTbl.amount) + SUM(SupplyTbl.supply) as amount
, SUM(IssuedTbl.issued) as issued
, (SUM(amount) - SUM(issued)) as balance
FROM AccntTbl LEFT JOIN
(SELECT id, COALESCE(SUM(supply), 0) AS supply, date FROM SupplyTbl
GROUP By id, date) AS SupplyTbl
ON AccntTbl.id = SupplyTbl.id AND (MONTH(SupplyTbl.date) BETWEEN
1 AND 2)
LEFT JOIN
(SELECT id, COALESCE(SUM(issued),0) as issued, date from IssuedTbl
GROUP By id, date )
ON AccntTbl.id = IssuedTbl.id AND (MONTH(IssuedTbl.date) BETWEEN
1 AND 2)
WHERE (YEAR(AccntTbl.date) = 2016)
GROUP By AccntTbl.id, AccntTbl.accnt
;
在sql中,NULL
添加的任何内容都是NULL
。因此,如果您未使用COALESCE
,则在您的子查询中,您将使用NULL
添加您的值,因此您无法获得所需的结果。