sql:在选择一种类型的条目而不是另一种类型的条目时,如何忽略select语句中的重复项?

hfyxw5xn  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(334)

每个条目都有一个id(数字和字母的随机字符串)、一个名称(字符串)和一个类型(字符串“a”或“b”)。
有些条目具有相同的id和名称,但类型不同。
我试图编写一个select语句,当有一个条目使用类型a的相同id时,它会忽略类型b的条目。
据我所知,distinct不起作用,因为它依赖于所有列中的元素匹配,不能基于一列进行区分。

uubf1zoe

uubf1zoe1#

有一种方法。。。

with type_a as
        (select distinct id, name, type
        from table_name 
        where type = 'A'
        ),
        type_b as
        (select distinct id, name, type
        from table_name
        where type = 'B' 
        and id not in (select id from type_a)
        )
    select * from type_a
    union
    select * from type_b
3b6akqbq

3b6akqbq2#

使用 NOT EXISTS :

select t.*
from tablename t
where t.type = 'A'
or not exists (select 1 from tablename where id = t.id and name = t.name and type = 'A')

如果 name 不应涉及该情况,则使用以下方法:

or not exists (select 1 from tablename where id = t.id and type = 'A')

或使用 RANK() 窗口功能:

select t.id, t.name, t.type
from (
  select t.*
    rank() over (partition by id, name order by case when type = 'A' then 1 else 2 end) rnk 
  from tablename
) t
where t.rnk = 1

或删除 namepartition 如果不相关。

相关问题