在SQL Server表的多行中查找重复的**值集**
我有一个SQL Server数据库表,其中包含以下示例数据:在SQL Server表的多行中查找重复的**值集**,sql,sql-server,Sql,Sql Server,我有一个SQL Server数据库表,其中包含以下示例数据: ProductID GenericID MG --------------------------------- 1 1 2g 1 2 5g 2 2 5g 3 1 2g 3 2
ProductID GenericID MG
---------------------------------
1 1 2g
1 2 5g
2 2 5g
3 1 2g
3 2 5g
4 1 2g
5 1 2g
5 3 7g
6 2 5g
7 1 2g
8 1 2g
我想找出选择数据的查询
ProductID=1
,那么查询应该检查与ProductID=1
关联的GenericID
ProductID=1
,则查询将检查GenericID=
1和2是否与ProductID=1
关联ProductID
且仅具有GenericID=1和2的行
ProductID=1
,输出有四行,因为只有ProductID 3具有与ProductID=1
相同的GenericID
ProductId=1
,那么我想获得所有行,它们的GenericID
值与ProductId=1
值完全相同,这是示例数据中的{1,2}
。我正在与查询逻辑作斗争
例如,我选择了ProductID=1
,这是我想要的输出,如下所示,因为ProductID
3与ProductID
1具有相同的GenericID
值集
ProductID GenericID MG
-------------------------------
1 1 2g
1 2 5g
3 1 2g
3 2 5g
GenericID
可以为on或多个动态值
另一个示例-如果我选择ProductID=7
,这就是我想要的输出:
在本例中-它将只获得只有GenericID=1的结果,因为ProductID
=7只有GenericID
=1。任何具有GenericID=1
的productID集,以及该集包含其他GenericID
的productID集都将被忽略
ProductID GenericID MG
------------------------------
7 1 2g
8 1 2g
4 1 2g
我需要找到查询以选择所需的输出。
我希望所有产品都具有与谓词产品相同的通用id集。最简单的方法可能是使用
string\u agg()
:
Gordon,非常感谢您的及时回复,基本上我忘了通知您我正在使用SQL 2014,这就是为什么string_agg():操作函数对我没有帮助,但我真的很感谢您的帮助和及时回复,让我度过了美好的一天。在这里,我在您的另一个查询的帮助下创建了我的查询,您成为了对我非常有用的资源
select PG.PID2 as Alternatives
from (select d1.ProductID as PID1, d2.ProductID as PID2
from (select distinct ProductID from ProductsGenerics Where ProductID=@PID) d1 cross join
(select distinct ProductID from ProductsGenerics) d2
) PG left outer join
ProductsGenerics e1
on e1.ProductID = PG.PID1 full outer join
ProductsGenerics e2
on PG.PID2 = e2.ProductID and e1.genericid = e2.GenericID-- and e1.MG = e2.MG
group by PG.PID1, PG.PID2
having SUM(case when e1.GenericID is null then 1 else 0 end) = 0 and
SUM(case when e2.GenericID is null then 1 else 0 end) = 0
select PG.PID2 as Alternatives
from (select d1.ProductID as PID1, d2.ProductID as PID2
from (select distinct ProductID from ProductsGenerics Where ProductID=@PID) d1 cross join
(select distinct ProductID from ProductsGenerics) d2
) PG left outer join
ProductsGenerics e1
on e1.ProductID = PG.PID1 full outer join
ProductsGenerics e2
on PG.PID2 = e2.ProductID and e1.genericid = e2.GenericID-- and e1.MG = e2.MG
group by PG.PID1, PG.PID2
having SUM(case when e1.GenericID is null then 1 else 0 end) = 0 and
SUM(case when e2.GenericID is null then 1 else 0 end) = 0