2011-12-05 39 views
1

我有5張桌子已經相關數據.. 它看起來是這樣的一個數據庫..我應該如何參加這五個表&SUM多列從多個表

Database Diagram with 5 tables

表「 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] & [associate_bycash.bycashajf]對於特定的時間範圍。(f的SUM或例如。 05/12/2011 07/12/2011到)

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預先

回答

1

您不能混合這樣的內連接和外連接。當您使用左外連接時,它將返回右表中的空記錄,以確保左邊表中的所有行按預期返回。但是,如果您嘗試使用INNER連接將右手錶連接到另一個表,則空記錄將被過濾掉,因爲在其他表中沒有匹配的空記錄。

就你而言,這是發生在你加入payin時。您會得到一行aid = 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

+0

我執行了查詢..現在它返回的所有值,除了2011年5月12日返回的金額是60400 .. [associate_bycash.bycashajf]金額越來越多包括在內.. btw .. thanx。這是我學到的一件很酷的事情.. – Avrajit