如何连接这两个表
select m.caseno,
sum(m.BalanceAmount) GOVT from TABLE1 m
inner join TABLE2 g on m.Code = g.Code
where g.alpha in ('a','b','c')
group by m.caseno
输出 案例GOVT
select m.caseno,
sum(m.BalanceAmount) MIF from TABLE1 m
inner join TABLE2 g on m.Code = g.Code
where g.alpha in ('d','e')
group by m.caseno
输出 案例MIF
我希望他们加入一个查询 案例GOVT | MIF
答案 0 :(得分:3)
如果您不想触摸现有查询,则可以对它们执行FULL OUTER JOIN
:
select
coalesce(a.caseno, b.caseno) as caseno,
a.govt,
b.mif
from ( -- first query
select m.caseno,
sum(m.BalanceAmount) GOVT from TABLE1 m
inner join TABLE2 g on m.Code = g.Code
where g.alpha in ('a','b','c')
group by m.caseno
) a
full outer join ( -- second query
select m.caseno,
sum(m.BalanceAmount) MIF from TABLE1 m
inner join TABLE2 g on m.Code = g.Code
where g.alpha in ('d','e')
group by m.caseno
) b on a.caseno = b.caseno
FULL OUTER JOIN
和COALESCE()
都是必要的,以连接可能在任一查询中显示的不匹配行。
答案 1 :(得分:1)
用例何时显示为2列。
select m.caseno,
sum(case when g.alpha in ('d','e') then m.BalanceAmount else 0 end) MIF ,
sum(case when g.alpha in ('a','b','c') then m.BalanceAmount else 0 end) GOVT
from TABLE1 m
inner join TABLE2 g on m.Code = g.Code
where g.alpha in ('a','b','c','d','e')
group by m.caseno
答案 2 :(得分:-1)
我认为您必须执行完全外部联接。试试这个。
SELECT *
FROM (
select m.caseno,
sum(m.BalanceAmount) GOVT from TABLE1 m
inner join TABLE2 g on m.Code = g.Code
where g.alpha in ('a','b','c')
group by m.caseno
) AS tab1
FULL OUTER JOIN (
select m.caseno,
sum(m.BalanceAmount) MIF from TABLE1 m
inner join TABLE2 g on m.Code = g.Code
where g.alpha in ('d','e')
group by m.caseno
) AS tab2
ON tab2.caseno = tab1.caseno