【问题标题】:PostgreSQL- get records with unique column combinationPostgreSQL-获取具有唯一列组合的记录
【发布时间】:2019-11-09 16:59:54
【问题描述】:
我想在 postgresql 中选择具有唯一列组合的记录,但它似乎不适用于 distinct,因为 distinct 只会删除重复项。
例子
ID A B
01 1 2
02 1 2
03 1 3
04 2 4
05 1 4
06 2 4
07 2 5
08 1 3
在此示例中,ID 为 05 和 07 的行具有唯一组合 AB,我如何获取这些记录
SELECT ...
【问题讨论】:
标签:
postgresql
unique
distinct
【解决方案1】:
NOT EXISTS:
select t.* from tablename t
where not exists (
select 1 from tablename
where id <> t.id and a = t.a and b = t.b
)
或者用COUNT()窗口函数:
select t.id, t.a, t.b
from (
select *, count(id) over (partition by a, b) counter
from tablename
) t
where t.counter = 1
或者聚合:
select max(id) id, a, b
from tablename
group by a, b
having count(id) = 1
或者使用排除匹配行的自我LEFT 连接:
select t.*
from tablename t left join tablename tt
on tt.id <> t.id and tt.a = t.a and tt.b = t.b
where tt.id is null
见demo。
结果:
| id | a | b |
| --- | --- | --- |
| 05 | 1 | 4 |
| 07 | 2 | 5 |