oracle—使用sql查询为特定条件填充两行

kcrjzv8t  于 2021-08-09  发布在  Java
关注(0)|答案(3)|浏览(391)
SK        |    Code       |   SIG_Code    | ID
----        -----------      ----------     ----                    
1              A             S               1
1              B             S               2
1              C             M               3
2              A             B               4
3              A             S               5
4              A             B               6
4              B             B               7

考虑到上表,我希望记录的代码是'a'和'b'。我试着写一个这样的查询,从表中选择*fromcode='a'和code='b'。但这似乎不管用。使用in-condition也不能提供所需的输出。有人能帮我建立这个查询吗?
谢谢您。

m528fe3b

m528fe3b1#

可以使用聚合:

select sk
from t
where code in ('A', 'B')
group by sk
having count(*) = 2;

这假设没有重复。如果允许重复,则使用 count(distinct code) = 2 .

pgpifvop

pgpifvop2#

您可以使用以下分析函数来获取整个记录:

select * from
(
 select t.*,
        count(distinct code) over (partition by sk) as cnt
   from yout_table t
  where code in ('A', 'B')
) 
where cnt = 2

上面的查询将为sk=1返回2条记录(代码为a和b),为sk=4返回2条记录
如果您希望id的所有记录都包含a和b(sk=1的3个记录),则可以使用以下代码:

select * from
(
 select t.*,
        count(distinct case when code in ('A', 'B') then code end) 
               over (partition by sk) as cnt
   from yout_table t
) 
where cnt = 2
ca1c2owp

ca1c2owp3#

i) 尝试使用子查询

select* from #table a
where code in( 'A', 'B')
and SIG_Code in (select SIG_Code from #table b where code in ('B') and a.sk=b.sk)

ii)使用case和count函数尝试下面的查询。

select sk, code, SIG_Code,ID from
(
 select t.*,
        count(case when code = 'b' then 'a' end) over (partition by sk) as cnt
   from #table t
  where code in ('A', 'B')
) a
where cnt = 1

相关问题