2016-02-12 68 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;