在每个组的列中处理值

时间:2018-07-19 03:18:29

标签: mysql sql database

我有一个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 个答案:

答案 0 :(得分:1)

您可以删除行:

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)
          );