SQL查询:加入union all查询的结果

时间:2016-02-12 03:04:00

标签: 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

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

如果我理解正确,请从id

中删除select
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;

答案 1 :(得分:0)

您的陈述中的问题是您有一个LEFT JOIN,它将始终包含联接左侧的所有行。

如果您正在执行A LEFT JOIN B ON ...,则始终将返回A中的所有行。如果A和B之间不匹配,则B的列值将为NULL。

您需要的是INNER JOIN,它只会返回A INNER JOIN B ON ...中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;