SQL:在选择一种类型的条目而不是另一种类型的条目时,如何忽略select语句中的重复项?
每个条目都有一个ID(数字和字母的随机字符串)、一个名称(字符串)和一个类型(字符串“a”或“B”) 某些条目共享相同的ID和名称,但具有不同的类型 我试图编写一个select语句,当有一个条目使用类型a的相同ID时,它会忽略类型B的条目 据我所知,DISTINCT不起作用,因为它依赖于所有列中的元素匹配,并且不能基于列进行区分。这里有一种方法SQL:在选择一种类型的条目而不是另一种类型的条目时,如何忽略select语句中的重复项?,sql,select,duplicates,distinct,Sql,Select,Duplicates,Distinct,每个条目都有一个ID(数字和字母的随机字符串)、一个名称(字符串)和一个类型(字符串“a”或“B”) 某些条目共享相同的ID和名称,但具有不同的类型 我试图编写一个select语句,当有一个条目使用类型a的相同ID时,它会忽略类型B的条目 据我所知,DISTINCT不起作用,因为它依赖于所有列中的元素匹配,并且不能基于列进行区分。这里有一种方法 with type_a as (select distinct id, name, type from tabl
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
使用
不存在
:
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')
如果名称
不应包含在该情况中,则使用以下方法:
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
或者从分区中删除名称
,如果它不相关