SQL查询:联接union all查询的结果

SQL查询:联接union all查询的结果,sql,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 In

我有以下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

如何实现此目的?

如果我理解正确,请从
选择中删除
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;

语句中的问题是有一个
左联接
,它将始终包括联接左侧的所有行

如果您在…
上执行左联接B,则将始终返回A中的所有行。如果A和B之间不匹配,则B的列值将为NULL

相反,您需要的是一个
内部联接
,它将只返回在…上的
内部联接B中a和B之间存在匹配的行。在您的情况下,这将只返回A中满足B中相应收入类型的行


如果要按Id对总和进行分组:

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的总和:

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;