Sql 在相同 table 上匹配完全相同的数据集

Sql Matching exact DataSets on same table

我有一个 table,其中包含如下数据:

Store,Product
a,         1
a,         2
b,         3
b,         2
c,         3
c,         1
d,         1
d,         2
d,         3

我正在尝试编写一个为我提供替代商店的查询,因此由于商店 d 销售商店 a 销售的所有产品,因此它可以替代商店 a 但商店 a 不能替代商店 d因为它没有商店 d 销售的所有产品。

所以查询会 return 以下 table:

Store,Store Replacement
a,-         
b,-     
c,- 
d,a

*注意我不知道如何制作 table,所以 ',' 代表列的分隔。 - 等于 space

中的空格

这是一个有效的版本:

select sp.store, sp2.store
from (select sp.*, count(*) over (partition by store) as numproducts
      from @storeproduct sp
     ) sp join
     @storeproduct sp2
     on sp.product = sp2.product and sp.store <> sp2.store
group by sp.store, sp2.store, numproducts
having count(sp2.product) = numproducts;

Here 是 SQL Fiddle.