2017-06-14 58 views
0

在我的postgres表中,我有兩列興趣點:idname - 我的目標是隻保留id名稱中有多個值的記錄。換句話說,想保持id S作多個值和的所有記錄的值的至少一個爲B在一列中設置包含多個值的記錄

更新:我已經嘗試添加WHERE EXISTS下面的查詢,但這個不起作用

的樣本數據是這樣的:

> test 
    id name 
1 1 A 
2 2 A 
3 3 A 
4 4 A 
5 5 A 
6 6 A 
7 7 A 
8 2 B 
9 1 B 
10 2 B 

和輸出應該是這樣的:

> output 
    id name 
1 1 A 
2 2 A 
8 2 B 
9 1 B 
10 2 B 

如何寫一個查詢來選擇只有這些種類的記錄?

+0

因爲ID 6只具有一個不 –

回答

1

你似乎想:​​

select id, name 
from (select t.*, min(name) over (partition by id) as min_name, 
      max(name) over (partition by id) as max_name 
     from t 
    ) t 
where min_name < max_name; 
+0

的感謝記錄,並,這個工作,但我稍微修改我的問題 - 是否有納入辦法「 WHERE EXISTS'在查詢中? –

+1

@the_darkside:在收到答案後改變問題並不被認爲是禮貌的。 –

1

這是可以做到用EXISTS:根據您的描述

select id, name 
from test t1 
where exists (select * 
       from test t2 
       where t1.id = t2.id 
       and t1.name <> t2.name) -- this will select those with multiple names for the id 
    and exists (select * 
       from test t3 
       where t1.id = t3.id 
       and t3.name = 'B') -- this will select those with at least one b for that id 
0

那裏爲他們的ID不止一個名字照耀了這些記錄,對不對? 這可能會在「SQL」來表述如下:

select * from table t1 
where id in (
    select id 
    from table t2 
    group by id 
    having count(name) > 1) 
相關問題