首页 > 解决方案 > 选择所有字段满足条件的所有数据

问题描述

请帮我编写一个 sql 查询。有一个数据库(里面有更多的列,但我认为这并不重要)。如何获取所有的seller_id,这里所有的店铺都关门了,如果至少有一个店铺开着或者暂时关门了,那就不行了。在我下面给出的数据的情况下,应该只显示seller_id 1 和4。提前致谢

seller_id | shop_id  | shop_status
-------------------------------------
    1     |   10     |   close
    2     |   11     |   open
    1     |   12     |   close
    2     |   13     |   temporarily_close
    3     |   14     |   open
    3     |   15     |   close
    4     |   16     |   close

标签: sqloracle

解决方案


您可以使用聚合和having子句:

select seller_id
from t
group by seller_id
having min(shop_status) = max(shop_status) and min(shop_status) = 'close';

如果您有单独的卖家列表,那么not exists可能会更快:

select s.*
from sellers s
where not exists (select 1
                  from t
                  where t.seller_id = s.seller_id and
                        t.shop_status <> 'close'
                 );

编辑:

如果shop_status可以NULL并且您想排除这些,那么您可以使用:

select seller_id
from t
group by seller_id
having min(shop_status) = max(shop_status) and
       min(shop_status) = 'close' and
       count(*) = count(shop_status);

和:

select s.*
from sellers s
where not exists (select 1
                  from t
                  where t.seller_id = s.seller_id and
                        (t.shop_status <> 'close' or t.shop_status is null)
                 );

推荐阅读