PostgreSQL-通过唯一的列组合获取记录

我想选择在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 ...
mlt9966 回答:PostgreSQL-通过唯一的列组合获取记录

使用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   |
本文链接:https://www.f2er.com/3132022.html

大家都在问