sql - select 具有多个相同列的所有行

sql - select all rows that have all multiple same cols

我有一个有 4 列的 table。

我需要在一天内找到所有 products_id 具有相同 label_id(例如 4)的所有 store_id。

例如:

store_id | label_id | product_id | data|
   4          4           5         9/2
   5          4           7         9/2
   4          3           12        9/2
   4          4           7         9/2   

所以它应该 return 4,因为它是唯一一家在一天内包含标签为 4 的所有可能产品的商店。

我试过这样的事情:

(select store_id, date
from table
where label_id = 4
group by store_id, date
order by date)

我不知道怎么写外部查询,我试过:

select * from table
where product_id = all(Inner query)

但是没用。

谢谢

这是一种方法:

SELECT date, store_id
FROM yourTable
GROUP BY date, store_id
HAVING COUNT(DISTINCT product_id) = (SELECT COUNT(DISTINCT product_id)
                                     FROM yourTable t2
                                     WHERE t2.date = t1.date)
ORDER BY date, product_id;

此查询以非常简单的方式读取,它说要在某个日期查找所有商店的不同产品计数与同一天的不同产品计数相同的所有产品。

我可能会聚合成字符串或数组中的产品列表:

with products_per_day_and_store as
(
  select
    store_id,
    date,
    string_agg(distinct product_id order by product_id) as products
  from mytable
  where label_id = 4
  group by store_id, date
)
, products_per_day
(
  select
    date,
    string_agg(distinct product_id order by product_id) as products
  from mytable
  where label_id = 4
  group by date
)
select distinct ppdas.store_id
from products_per_day_and_store ppdas
join products_per_day ppd using (date, products);

从您的问题中不清楚标签是特定于给定的一天还是整个时期。但蒂姆的答案的变体似乎是合适的。对于 任何 标签:

SELECT t.date, t.label, t.store_id
FROM t
GROUP BY t.date, t.label, t.store_id
HAVING COUNT(DISTINCT t.product_id) = (SELECT COUNT(DISTINCT t2product_id)
                                       FROM t t2
                                       WHERE t2.label = t.label
                                      );

对于特定标签:

SELECT t.date, t.store_id
FROM t
WHERE t.label = 4
GROUP BY t.date,t.store_id
HAVING COUNT(DISTINCT t.product_id) = (SELECT COUNT(DISTINCT t2product_id)
                                       FROM t t2
                                       WHERE t2.label = t.label
                                      );

如果标签特定于日期,那么您也需要在外部查询中进行比较。