2016-02-12 64 views
0

下面我有以下SQL查詢:SQL查詢:加入工會的結果,所有查詢

select SUM(Amount) Amount 
from 
    (
     select Amount from IncomeSource1 
     union all 
     select Amount from IncomeSource2 
    ) inc 

現在我需要過濾此表的基礎上的一些類型,它是在不同的表中的結果。比方說,連接會是這樣:

select Amount 
from IncomeSource1 ic1 
    left join IncomeType it on it.id = ic1.id 
where it.IncomeType = 1 

我想低於此,但沒有運氣,我仍然得到大量的全部總和。

select Id, SUM(Amount) Amount 
from 
    (
     select Id, Amount from IncomeSource1 
     union all 
     select Id, Amount from IncomeSource2 
    ) inc 
    left join IncomeType it on it.id = inc.id and it.IncomeType = 1 

我該如何做到這一點?

回答

0

如果我理解正確的話,從select刪除id

select SUM(Amount) as Amount 
from (select Id, Amount from IncomeSource1 
     union all 
     select Id, Amount from IncomeSource2 
    ) inc left join 
    IncomeType it 
    on it.id = inc.id and it.IncomeType = 1; 
0

在發言的問題是,你有一個LEFT JOIN將始終包括的加入左側的所有行。

如果您在做A LEFT JOIN B ON ...這將總是返回A中的所有行。如果A和B之間沒有匹配,則B的列值將爲NULL。

你需要的是一個INNER JOIN,它只返回在A INNER JOIN B ON ...之間A和B匹配的行。你的情況,這隻會返回一個如果你想通過ID分組的款項滿足於B.


相應的收益類型行:

select Id, SUM(Amount) Amount 
from 
    (
     select Id, Amount from IncomeSource1 
     union all 
     select Id, Amount from IncomeSource2 
    ) inc 
    inner join IncomeType it on it.id = inc.id and it.IncomeType = 1 
group by id; 

如果你想總和對於所有Id's:

select SUM(Amount) Amount 
from 
    (
     select Id, Amount from IncomeSource1 
     union all 
     select Id, Amount from IncomeSource2 
    ) inc 
    inner join IncomeType it on it.id = inc.id and it.IncomeType = 1;