table 商店有两列,例如 store_id 和产品。写一个 SQL 查询来查找只卖洗发水和饼干的 store_id

table stores has two columns like store_id and products. Write a SQL query to find store_ids which sell only shampoo and biscuit

商店应该只卖两种产品,也只卖洗发水和饼干

例如

输出:

我的查询:-

SELECT *
FROM (SELECT store_id AS gp_str
      FROM (SELECT store_id,
                   COUNT(product) AS prd_cnt
            FROM stores
            GROUP BY store_id) x
      WHERE x.prd_cnt = 2) y
     LEFT JOIN stores ON y.gp_str = stores.store_id;

我的查询给出了只销售两种产品的商店的结果,但我想要的是只销售洗发水和饼干两种产品的商店。

SELECT store_id
FROM stores
GROUP BY store_id
HAVING COUNT(DISTINCT product) = 2
    AND COUNT(*) = SUM(CASE WHEN product IN ('shampoo','biscuit') THEN 1 ELSE 0 END);