根据某些条件psql

时间:2016-12-07 13:29:36

标签: psql

考虑这种情况:

有一个表T (name,habit),其中名称和习惯的组合是表T的主键。

假设数据如下:

name | habit 
a1 | smoking
a1 | drinking
a2 | sleeping
a3 | jogging
a2 | jogging
a4 | sleeping

现在我想选择具有所有习惯的名字。显然,a2,a3a4有共同的习惯,因此应将其过滤掉。

所以输出应该像

输出:

name
a1

我的问题:

如何在psql中使用except执行此操作?

1 个答案:

答案 0 :(得分:0)

您不需要except

t=# with a as (
  select *,count(1) over (partition by habit)
  from t
)
select distinct name
from a
where count = 1;
 name
------
 a1
(1 row)

模式:

t=# create table T (name text,habit text);
CREATE TABLE
Time: 14.162 ms
t=# copy t from stdin delimiter '|';
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> a1 | smoking
a1 | drinking
a2 | sleeping
a3 | jogging
a2 | jogging
a4 | sleeping>> >> >> >> >>
>> \.
COPY 6
Time: 3216.573 ms