代码之家  ›  专栏  ›  技术社区  ›  user2181948

处理每个组的列中的值

  •  0
  • user2181948  · 技术社区  · 7 年前

    我有一个mysql表,其中列出了他们从中购买的客户和商店分支,如下所示:

        customer_id   |   branch_id   |   is_major_branch
        -----------------------------------------------
            5               24                1
            5               83                0
            5               241               0
            8               66                0
            8               72                0
            9               15                1
            16              31                1
            16              61                1
    

    is_major_branch 如果那家分店特别大的话,是1。

    如何删除客户在小分行购物的所有行(is_major_branch=0)。 除了 如果客户只在一家小分店购物示例结果集:

        customer_id   |   branch_id   |   is_major_branch
        -----------------------------------------------
            5               241               1
            8               66                0
            8               72                0
            9               15                1
            16              31                1
            16              61                1
    

    注意,客户8只在一个小分店购物过,所以我们从删除中忽略了它们。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Gordon Linoff    7 年前

    您可以删除行执行以下操作:

    delete t
        from t join
             (select customer_id, max(is_major_branch) as max_is_major_branch
              from t
              group by customer_id
             ) tt
             on t.customer_id = tt.customer_id
        where t.is_major_branch = 0 and tt.max_is_major_branch = 1;
    

    如果你只是想 select 查询,然后使用 exists :

    select t.*
    from t
    where not (t.is_major_branch = 0 and
               exists (select 1 from t t2 where t2.customer_id = t.customer_id and t2.is_major_branch = 1)
              );