SQL:如何忽略 select 语句中的重复项,同时优先选择一种类型的条目?
SQL: How do I ignore duplicates in a select statement while preferring one type of entry over another?
每个条目都有一个 ID(由数字和字母组成的随机字符串)、一个名称(字符串)和一个类型(字符串“A”或“B”)。
有些条目共享相同的 ID 和名称,但类型不同。
我正在尝试编写一个 select 语句,当存在使用类型 A 的相同 ID 的条目时忽略类型 B 的条目。
据我了解,DISTINCT 将无法工作,因为它依赖于所有列中匹配的元素,并且无法根据列进行区分。
这是一种方法...
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
使用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()
window函数:
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
如果不相关,则从 partition
中删除 name
。
每个条目都有一个 ID(由数字和字母组成的随机字符串)、一个名称(字符串)和一个类型(字符串“A”或“B”)。
有些条目共享相同的 ID 和名称,但类型不同。
我正在尝试编写一个 select 语句,当存在使用类型 A 的相同 ID 的条目时忽略类型 B 的条目。
据我了解,DISTINCT 将无法工作,因为它依赖于所有列中匹配的元素,并且无法根据列进行区分。
这是一种方法...
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
使用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()
window函数:
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
如果不相关,则从 partition
中删除 name
。