【问题标题】:SQL: How do I ignore duplicates in a select statement while preferring one type of entry over another?SQL:我如何在选择语句中忽略重复项,同时更喜欢一种类型的条目而不是另一种?
【发布时间】:2020-11-04 06:29:36
【问题描述】:
每个条目都有一个 ID(数字和字母的随机字符串)、一个名称(字符串)和一个类型(字符串“A”或“B”)。
一些条目共享相同的 ID 和名称,但具有不同的类型。
我正在尝试编写一个选择语句,当存在使用相同类型 A 的 ID 的条目时忽略 B 类型的条目。
据我了解,DISTINCT 不起作用,因为它依赖于所有列中匹配的元素,并且不能基于列进行区分。
【问题讨论】:
标签:
sql
select
duplicates
distinct
【解决方案1】:
这是一种方法...
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
【解决方案2】:
使用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
如果不相关,则将name 从partition 中删除。