2014-02-13 23 views
0

嗨我正在開發VS 2010,C#和SQLCe數據庫中的應用程序。內部加入查詢不正確的結果

我從3個表分別收入,Expence和交易生成報告。

表結構如下:

收入:

Income

Expence:

expence

交易:

trans

爲此,我寫了查詢

select t.tDate as [Date], t.tDescription as [Detail],e.eAmount as [Debit], 
i.iAmount as [Credit], t.balance as [Balance] 
from Transactions t 
    inner join Expence e on t.pid=e.pid 
    join Income i on t.pid=i.pid 
where t.pid='11' 

但是當我運行此查詢我剛開

result

32,我想結果應該是像下面一個銀行對賬單。 final

根據我理解的查詢是不正確的。

我們如何編寫查詢來獲得像這樣的結果?

回答

0

您必須使用left join,不能使用加入。因爲left返回表from中的所有案例,並且表Expence e Income中存在案例。

select t.tDate as [Date], t.tDescription as [Detail],e.eAmount as [Debit], 
    i.iAmount as [Credit], t.balance as [Balance] 
from Transactions t 
    left join Expence e on t.pid=e.pid 
    left join Income i on t.pid=i.pid 
where t.pid='11' 
0

如果我這樣做是正確的加入從Expence表中的項目與事務表,你應該使用PID和開齋節並加入來自收入,你應該使用PID和IID,項目,因此項目的選擇看起來類似的東西:

select t.tDate as [Date], t.tDescription as [Detail],e.eAmount as [Debit], 
i.iAmount as [Credit], t.balance as [Balance] 
from Transactions t 
    inner join Expence e on t.pid=e.pid and t.eId = e.eId 
    join Income i on t.pid=i.pid and t.iId = i.iId 
where t.pid='11'