我有一个包含5个具有相关数据的表的数据库。 它看起来像这样..
表“associate_payin_ad”存储注册日期&附件id。实际上,附件只是一张纸,可以有零个或多个“Payin”或“Associate”条目。
'payin'& 'associate'表格有多种付款模式(如现金,支票,bdcash,bdcheque)[金额]& [付款]专栏.. bycash,bycheque,bybdcash& bybdcheque,我只展示了'bycash'表格。
如果表格中填写了以下给定的数据..
[associate_payin_ad] Table:
adid | date_register | annexure_id
1 | 05/12/2011 | 1
2 | 05/12/2011 | 2
3 | 06/12/2011 | 1
4 | 07/12/2011 | 1
[payin] Table:
fid | amount | adid
1 | 10000 | 1 [this entry was made on 05/12/2011 in annexure no 1]
2 | 10000 | 1 [this entry was made on 05/12/2011 in annexure no 1]
3 | 40000 | 2 [this entry was made on 05/12/2011 in annexure no 2]
4 | 10000 | 4 [this entry was made on 07/12/2011 in annexure no 1]
[payin_bycash] Table:
fid | bycash
1 | 10000
2 | 10000
3 | 40000
4 | 10000
[associate] table...
aid | payment | adid
1 | 200 | 1 [this entry was made on 05/12/2011 in annexure no 1]
2 | 200 | 3 [this entry was made on 06/12/2011 in annexure no 1]
[associate_bycash] table...
aid | bycashajf
1 | 200
2 | 200
我需要[payin_bycash.bycash]&的SUM。 [associate_bycash.bycashajf]针对特定日期范围..(例如,2011年12月12日至2011年12月7日)
date_register | amount
05/12/2011 | 60200
06/12/2011 | 200
07/12/2011 | 10000
我从昨天开始试图找出合适的查询,我一直在圈子里跑来跑去。我能想出的最好的就是这个,但是徒劳无功:
SELECT apad.date_register,
SUM(ISNULL(pica.cash_in_hand, 0)) + SUM(ISNULL(aca.bycashajf, 0)) AS amount
FROM associate_payin_ad AS apad LEFT OUTER JOIN
payin AS pi ON apad.adid = pi.adid INNER JOIN
payin_bycash AS pica ON pi.fid = pica.fid
LEFT OUTER JOIN associate AS asso ON apad.adid = asso.adid INNER JOIN
associate_bycash AS aca ON asso.aid = aca.aid
WHERE (apad.date_register BETWEEN @date_initial AND @date_final)
GROUP BY apad.date_register
上面的查询只返回我..
date_register | amount
05/12/2011 | 20400
我做错了什么?
提前thnx答案 0 :(得分:1)
你不能像这样混合内部和外部联接。当您使用左外连接时,它将在右侧表中返回空记录,以确保左手表中的所有行都按预期返回。但是,如果您尝试使用INNER连接将右侧表连接到另一个表,则将过滤掉空记录,因为在另一个表中不会有匹配的空记录。
在您的情况下,当您加入payin时会发生这种情况。你会得到一行援助= 3,但是当你尝试加入payin_bycash时,那一行被过滤掉了,因为payin中不存在aid = 3.你的联合关联也存在同样的问题。
解决此问题的最佳方法是将联接保留为子查询(或者您可以使用CRE执行此操作)。试试这个:
SELECT apad.date_register,
SUM(ISNULL(pica.cash_in_hand, 0)) + SUM(ISNULL(aca.bycashajf, 0)) AS amount
FROM associate_payin_ad AS apad
LEFT OUTER JOIN
(
SELECT payin_bycash.cash_in_hand
FROM payin
INNER JOIN payin_bycash ON payin.fid = payin_bycash.fid
) pi ON apad.adid = pi.adid
LEFT OUTER JOIN
(
SELECT associate_bycash.bycashajf
FROM associate
INNER JOIN associate_bycash ON associate.aid = associate_bycash.aid
) asso ON apad.adid = asso.adid
WHERE (apad.date_register BETWEEN @date_initial AND @date_final)
GROUP BY apad.date_register
另外,请阅读:http://weblogs.sqlteam.com/jeffs/archive/2007/10/11/mixing-inner-outer-joins-sql.aspx