【问题标题】:I want to remove some customers associated with one brand from other brand in same column in PostgreSQL我想在 PostgreSQL 的同一列中从另一个品牌中删除一些与一个品牌相关的客户
【发布时间】:2020-09-28 12:13:24
【问题描述】:

我需要在最终输出中从品牌中删除存在于 x 和 y 品牌中的客户

Customer_id |brand 
   1        | a
   2        | a
   3        | a
   4        | a
   1        | x
   3        | y
   5        | z

最终输出应该是这样的 -

Customer_id |brand

   2        | a
   4        | a
   1        | x
   3        | y
   5        | z

【问题讨论】:

    标签: sql postgresql subquery where-clause window-functions


    【解决方案1】:

    你可以使用exists:

    select t.*
    from mytable t
    where brand <> 'a' or not exists (
        select 1 from mytable t1 where t1.customerid = t.customerid and t1.brand <> 'a'
    )
    

    或者,您可以使用窗口函数:

    select
    from (
        select t.*, bool_and(brand = 'a') over(partition by customerid) has_only_a
        from mytable t
    ) t
    where brand <> 'a' or has_only_a
    

    【讨论】:

      猜你喜欢
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 2019-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多