当您union
有两个结果集时,组合集中的列名取自联合的第一个分支。你有效地得到了:
select statusA from test
union
select statusB as statusA from test1
statusB
所以在结果集中没有可以使用的。您可能想要执行以下操作:
select case when (select nvl(max(statusA), 'N') from test) = 'N'
and (select nvl(max(statusB), 'N') from test1) = 'N'
then 'N' else 'Y' end
from dual
虽然我不太确定您是否希望每个表都有一个值,以及您正在尝试做的事情。
好的,然后,使用链接两个表的 ID 值,并且给定的 ID 在一个或两个表中,您可以使用完整的外部联接:
select coalesce(t.id, t1.id) as id, t.statusa, t1.statusb,
case when nvl(statusa, 'N') = 'N' and nvl(statusb, 'N') = 'N'
then 'N' else 'Y' end as flag
from test t
full outer join test1 t1 on t1.id = t.id
order by coalesce(t.id, t1.id);
使用您添加到问题中的值 - 并假设“无数据”意味着该表中没有与另一个 ID 中存在的 ID 匹配的行 - 这为您提供:
ID STATUSA STATUSB FLAG
---------- ------- ------- ----
1 Y Y
2 N N
3 Y Y
4 N N
5 Y Y Y
6 Y N Y
7 N
8 N N N
SQL 小提琴。