在postresql

时间:2016-02-12 22:53:56

标签: sql postgresql unique

我需要类似的东西:

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中

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

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

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

2;"other";"xoxox"

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

使用count(*)作为窗口函数:

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);

答案 1 :(得分:0)

您可以在不需要子查询的情况下过滤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