2016-12-07 12 views
0

に基づいて他のすべての行以外の行を選択し、このシナリオを検討:いくつかの条件にpsql

名や習慣の組み合わせが表Tの主キーであるテーブルT (name,habit)があります。

は、次のようにデータがあるとします

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

今私はユ​​ニークなように、すべての習慣を持っている名前を選択します。ここで明らかにa2,a3a4には共通点があり、除外すべきです。

ので、出力は

OUTPUTのようにする必要があります:

name 
a1 

私の質問:

がどのように私はこのpsqlでexceptを使用して行うことができますか?

+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 
関連する問題