Sql server 有没有一种简单的方法来检索包含ID列表的组合?
这是要搜索的输入和数据。正在尝试查找包含SourceID 62和67的SourceCombinationID。到目前为止,我只有一个查询返回包含62或67的SourceCombinationId,但我需要获取同时包含-62和67的SourceCombinationId(它们可能包含更多源,但它们必须至少包含这两个源) 提前谢谢你Sql server 有没有一种简单的方法来检索包含ID列表的组合?,sql-server,Sql Server,这是要搜索的输入和数据。正在尝试查找包含SourceID 62和67的SourceCombinationID。到目前为止,我只有一个查询返回包含62或67的SourceCombinationId,但我需要获取同时包含-62和67的SourceCombinationId(它们可能包含更多源,但它们必须至少包含这两个源) 提前谢谢你 DECLARE @SourceIDs_In TABLE (SourceID INT); INSERT INTO @SourceIDs_In VALUES (62), (
DECLARE @SourceIDs_In TABLE (SourceID INT);
INSERT INTO @SourceIDs_In VALUES (62), (67);
-- data to search
DROP TABLE IF EXISTS #All;
CREATE TABLE #All ( [SourceId] INT, [SourceCombinationId] INT )
INSERT INTO #All ([SourceId], [SourceCombinationId])
VALUES
(67, 80),
(66, 81),
(68, 82),
(61, 82),
(62, 83), --
(67, 83), --
(68, 84),
(62, 85),
(64, 86),
(69, 87),
(65, 88),
(60, 88),
(67, 88),
(67, 89), --
(62, 89), --
(66, 89); --
-- expected result
/*
[SourceCombinationId]
83
89
*/
SELECT * FROM #All ORDER BY SourceCombinationId, SourceId;
-- this returns SourceCombinationId that contain either 62 or 67 but not both
SELECT DISTINCT A.SourceCombinationId FROM #All A
INNER JOIN @SourceIDs_In SIDI ON SIDI.SourceID = A.SourceId
;
您可以比较每个SourceCombinationId的命中数,以查看它是否与中@SourceId\u的总计数相匹配。也就是说,如果少于所有匹配项,则SourceCombinationId没有所有源ID
SELECT A.SourceCombinationId,
count(*) TotalHits
FROM (
SELECT DISTINCT *
FROM #All
) A
INNER JOIN @SourceIDs_In SIDI ON SIDI.SourceID = A.SourceId
GROUP BY A.SourceCombinationId
HAVING count(*) >= (
SELECT count(*)
FROM @SourceIDs_In
)