有没有一种简单的方法来检索包含 ID 列表的组合?

时间:2021-01-21 16:34:27

标签: sql-server

这是要搜索的输入和数据。试图找到包含 SourceID 62 和 67 的 SourceCombinationIDs。到目前为止,我只有一个查询返回包含 62 或 67 的 SourceCombinationIds,但我需要获取同时包含 62 和 67 的 SourceCombinationIds(它们可能包含更多源,但它们有至少有这两个)。

先谢谢你!

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
;

1 个答案:

答案 0 :(得分:1)

您可以比较每个 SourceCombinationId 的点击次数,看看它是否与 @SourceIDs_In 的总数匹配。 IE。如果少于所有匹配项,则 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
        )