簡體   English   中英

為不同的值集過濾列

[英]Filtering a Column for distinct set of values

我有一張包含姓名、ID 和汽車的表格。

我想返回只有本田或福特的人的不同姓名和身份證。

如果他們有本田或福特,或者兩者都有,這沒關系並返回值。 但是如果他們同時擁有另一個品牌(例如下面的 bob 案例),則不要返回名稱/ID。

桌子:

Name ID   Car
BOB 21112 Honda  
Ame 32112 Honda 
BOB 21112 FORD
**BOB 21112 Dodge** --disqualifies bob from output
Ale 12322 Ford
Ame 32112 Ford
Sam 52412 Honda

Output:

Name ID   Car
Ame 21112 Honda, Ford   
Ale 32112 Ford 
Sam 52412 Honda

output 不一定要像上面那樣,只是想為滿足此條件的人識別不同的名稱和 ID。

我嘗試了以下類似的方法,但我認為如果一個名字有其他品牌的汽車,這也算案例。

Select t.Name, t.ID, t.Car
FROM table t
WHERE t.name = 'Honda' OR t.name = 'Ford'

我想返回只有本田或福特的人的不同姓名和身份證。

我建議使用聚合:

select name, id, array_agg(car)
from t
group by name, id
having count(*) filter (where car not in ('Honda', 'Ford')) = 0;

這會將汽車列表放入一個數組中。 如果您想要單獨的行(可能還有其他列),您可以使用 window 函數:

select t.*
from (select t.*,
             count(*) filter (where name not in ('Honda', 'Ford')) over (partition by name, id) as cnt
      from t
     ) t
where cnt = 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM