0

如何使用对偶将 2 个查询输出数据评估为一个。

我可以像下面那样做吗?,但给出错误提示找不到状态B。

 select case when (statusA is NULL or statusA ='N') and (statusB is NULL or statusB ='N') then 'N'
   else 'Y' from 
   (
     select statusA from test
     union
     select statusB from test1
   ) dual;

试图评估下表

表 1 中的状态 A 表 2 中的状态 B 结果
  Y 空或无数据 Y
  N 空或无数据 N
空或无数据 YY
空或无数据 NN
  年年
  年年
  空空 N
  神经网络

问候, 柴图哈拉

4

3 回答 3

1

当您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 小提琴

于 2013-09-06T10:23:09.103 回答
0

要在那里坚持您的原始查询,很容易在联合中对 statusa 和 statusb 列进行别名。请注意,我添加了每一列然后联合所有而不是联合并删除了双重别名,因为这是一个 Oracle 保留的“虚拟表”。

 select case when (statusA is NULL or statusA ='N') and (statusB is NULL or statusB ='N') then 'N'
   else 'Y' from 
   (
     select statusA, null as statusB from test
     union all
     select null as statusA, statusB from test1
   ) ;
于 2013-09-06T14:01:06.720 回答
0

让您的表 testa 成为:

id  statusa
1   Y
2   N
3   null or no data
4   null or no data
5   Y
6   Y
7   
8   N

和表testb:

id      statusb
1   null or no data
2   null or no data
3   Y
4   N
5   Y
6   N
7   
8   N

现在你可以:

SELECT STATUSA, STATUSB,  CASE WHEN new_statusa  = 'Y' OR new_statusb = 'Y' THEN 'Y' ELSE 'N' END RESULT
FROM
(SELECT STATUSA, STATUSB, CASE WHEN statusa IS NOT NULL AND statusa <> 'Y' THEN 'N' ELSE nvl(STATUSa,'N') END new_statusa,
     case when statusB is not null and statusB <> 'Y' THEN 'N' ELSE nvl(STATUSB,'N') end new_statusb
FROM TESTa
JOIN testb USING (id));
于 2013-09-06T11:03:15.680 回答