Oracle-是否仅从同一表中的另一列中检索具有不同关联值的列中的值?

c90pui9n  于 2022-10-04  发布在  Oracle
关注(0)|答案(2)|浏览(160)

我需要为以下内容编写一个Oracle SQL查询。

表“Employee”包含三列:eno、Sequence和Status of 3 Employees。我只需要检索那些同时具有“新”和“旧”状态的员工。因此,我不需要编号为C456的员工。请参见下面的预期产量。

最终预期产量如下:

xxe27gdn

xxe27gdn1#

您可以使用以下查询:

1) select *
     from employee a
    where exists (select 1 from employee b where b.ENO = a.ENO and b.status = 'New')
      and exists (select 1 from employee b where b.ENO = a.ENO and b.status = 'Old')
    order by 1,2;

ENO    SEQUENCE STATUS
---- ---------- -------
A101          1 New
A101          2 Old
A101          3 Old
A101          4 Old
B111          3 Old
B111          5 New
B111         25 New

2) select *
     from employee a
    where (select count(distinct b.status) 
             from employee b where b.ENO = a.ENO and b.status in ('New','Old')) = 2
    order by 1,2;

ENO    SEQUENCE STATUS
---- ---------- -------
A101          1 New
A101          2 Old
A101          3 Old
A101          4 Old
B111          3 Old
B111          5 New
B111         25 New

谢谢。

biswetbf

biswetbf2#

这里有一个使用count() over()而不使用inner joins的简单解决方案。

select  ENO
       ,Sequence
       ,Status
from   (
        select  t.*
                  ,count(distinct status) over(partition by eno) as cnt
        from    t
       ) t
where   cnt = 2

ENO|Sequence|状态
-|-|
A101|1|新增
A101|2|旧
A101|3|旧
A101|4|旧
B111|25|新增
B111|5|新增
B111|3|旧

Fiddle

相关问题