2016-12-07 16 views
0
的所有其他行的行

考虑这种情况:选择除了根据一些条件PSQL

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

假设数据如下:

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

现在我想选择哪个都习惯作为唯一的名称。这里明确的a2,a3a4有共同的习惯,所以他们应该被过滤掉。

所以输出应该像

OUTPUT:

name 
a1 

我的问题:

我怎样才能做到这一点使用except在psql里?

+0

你不需要'except'它 –

回答

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