PostgreSQL-获取具有唯一列组合的记录
PostgreSQL- get records with unique column combination
我想 select 在 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 ...
与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()
window函数:
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 |
我想 select 在 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 ...
与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()
window函数:
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 |