【问题标题】:Filtering a Column for distinct set of values为不同的值集过滤列
【发布时间】:2021-05-27 07:40:54
【问题描述】:

我有一张包含姓名、ID 和汽车的表格。

我想返回不同拥有本田或福特汽车的人的姓名和 ID。

如果他们有本田或福特,或者两者都有,这没关系并返回值。但是,如果他们同时有 AND 另一个品牌(例如以下 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

输出:

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

输出不一定要像上面那样,而只是想为满足此条件的人识别不同的名称和 ID。

我尝试了以下类似的方法,但我认为如果一个名字有其他品牌的汽车,这也会计算在内。

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

【问题讨论】:

    标签: sql postgresql snowflake-schema


    【解决方案1】:

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

    我建议使用聚合:

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

    这会将汽车列表放入一个数组中。如果您想要单独的行(可能还有其他列),您可以使用窗口函数:

    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;
    

    【讨论】:

      猜你喜欢
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 2020-10-23
      • 1970-01-01
      相关资源
      最近更新 更多