在 postgresql 中只获取唯一值

Getting only unique values in postresql

我需要这样的东西:

SELECT * FROM TABLE WHERE <value in column1 is always unique 
(if ever any value will be noticed more than once, then skip this row)>

在 postgresql 中。

所以如果我在 table 中有这些行:

1;"something";"xoxox"
2;"other";"xoxox"
3;"something";"blablabla"

然后继续查询,结果应该是:

2;"other";"xoxox"

有什么想法吗?

count(*)用作window函数:

select t.*
from (select t.*, count(*) over (partition by col1) as cnt
      from t
     ) t
where cnt = 1;

或者,您可以使用 not existsid 列:

select t.*
from t
where not exists (select 1 from t t2 where t2.col1 = t.col1 and t2.id <> t.id);

您可以过滤 count 而无需子查询:

SELECT t.col1
FROM t
GROUP BY col1
HAVING COUNT(*) = 1

可以使用 max 等聚合函数添加其他列,因为每个值只有 1 行:

SELECT t.col1, max(t.col2), max(t.col3)
FROM t
GROUP BY col1
HAVING COUNT(*) = 1