union子查询的一半返回null

时间:2015-08-14 17:34:35

标签: mysql sql

我想把我的钱栏分成两列(a和b型)

select case when t.type = 'a' then t.amount end,  
       case when t.type = 'b' then t.amount end, 
       t.accountNumber
    from (
    select 
    sum(t1.money) as amount,
    'a' as type,
    t1.accountNumber as accountNumber
    from table1 t1
    group by t1.accountNumber
    union
    select 
    sum(t2.money) as amount,
    'b' as type,
    t2.accountNumber as accountNumber
    group by t2.accountNumber
    from table2 t2  
    )t;

但是,现在类型b返回一堆'null'值。它似乎完全取决于工会之前的哪个表。例如,如果我把类型b放在类型a是,那么我会看到类型b值和类型值为null。我怎么能看到这两个值?

(第一次发帖所以我也很感激指点我可以更好地提问)谢谢! :)

1 个答案:

答案 0 :(得分:1)

根据您的评论,我认为下面的查询可能就是您想要的,它会为您提供如下输出:

sum_a   sum_b   accountNumber
100,00  NULL    1            -- account 1 is in table1
200,00  300,00  2            -- account 2 is in both tables
NULL    300,00  3            -- account 3 is in table2


select 
    max(case when t.type = 'a' then t.amount end) sum_a,  
    max(case when t.type = 'b' then t.amount end) sum_b, 
    t.accountNumber
from (
    select 
       sum(t1.money) as amount,
       'a' as type,
       t1.accountNumber as accountNumber
    from table1 t1
    group by t1.accountNumber
    union all
    select 
       sum(t2.money) as amount,
       'b' as type,
       t2.accountNumber as accountNumber
    from table2 t2  
    group by t2.accountNumber
)t
group by t.accountNumber;

或者,您可以使用full outer join来获得相同的结果:

select 
    sum(a.money) sum_a, 
    sum(b.money) sum_b, 
    coalesce(a.accountNumber, b.accountnumber) AccountNumber
from table1 a full outer join table2 b on a.accountnumber = b.accountnumber
group by coalesce(a.accountnumber, b.accountnumber);