使用 SQL 来识别存在指定唯一 grouping/combination 的实例

Using SQL to identify instances where there is a specified unique grouping/combination

在 Oracle SQL 中,我试图识别存在唯一记录组合的实例。例如,我有 table ITEMS,其中列出了连锁店出售的商品,其中 Store_ID 是位置,Item_ID 是商品:

Store_ID | Item_ID
01       | A
02       | A
02       | B
02       | C
03       | B
04       | A
04       | B
04       | C

...我想查询 table 以确定哪些商店 ID 出售所有商品('A'、'B' 和 'C' 的确切组合).上面 table 的结果将是 Store_IDs 02 和 04。

我试过以下方法,但没有返回任何行:

SELECT i.Store_ID
FROM Items i
WHERE i.Item_ID = 'A'
AND   i.Item_ID = 'B'
AND   i.Item_ID = 'C'

我也看过使用 CONTAINS,但似乎无法将其组合在一起。我确信这很容易,但我被卡住了。

如有任何帮助,我们将不胜感激。

做一个GROUP BY。使用 HAVING 确保所有 A、B 和 C 都存在。

SELECT i.Store_ID
FROM Items i
WHERE i.Item_ID in ('A', 'B', 'C')
group by i.Store_ID
having count(distinct i.Item_ID) = 3

概括以避免列出产品...

with x101 as (
select cast('01' as varchar2(20)) store_id, cast('A' as varchar2(20)) item_id from dual
union all 
select '02', 'A' from dual
union all 
select '02', 'B' from dual
union all 
select '02', 'C' from dual
union all 
select '03', 'B' from dual
union all 
select '04', 'A' from dual
union all 
select '04', 'B' from dual
union all 
select '04', 'C' from dual
union all 
select '05', 'C' from dual
union all 
select '05', 'B' from dual
union all 
select '06', 'C' from dual
),
x102 as (
SELECT 
   Store_ID, 
   item_id, 
   count(distinct Item_ID) over () as tot_prods,
   count(distinct Item_ID) over (partition by store_id) as store_tot_prods
FROM x101
)
select distinct Store_ID
FROM x102 
where store_tot_prods = tot_prods
;