我有一张这样的表
SourceId DestinationId
1 2
1 3
1 4
1 5
6 7
6 8
6 9
6 10
11 12
11 13
11 14
11 15
如果我将所有DestinationId传递给SP,我想选择SourceId。
例如:如果我在表格类型中传递(2,3,4,5,7,12)作为我的SP的destinationIds,它应该返回1,因为我通过了所有的destinationId即(2,3,4,5) )。 但它不应该返回6和11因为我只通过了7和12作为destinationId,而不是所有的DestinationId。
答案 0 :(得分:0)
在高级别,您需要两个计数。首先是每个来源的目的地总数。接下来是每个源的匹配目标数。一旦你有这些,比较一个与另一个。
在下面的示例中,我使用了两个common table expressions (CTEs),但您可以使用两个subqueries或temp tables。
一些提示可以帮助您避免未来的投票:
1 Stack Meta上的这个问题提供了一些发布good quality SQL questions的好方法。 1这page, from the help section,讨论了提供样本数据和预期产出的价值。
DECLARE @Sample TABLE
(
SourceId INT,
DestinationId INT
);
INSERT INTO @Sample
(
SourceId,
DestinationId
)
VALUES
(1, 2),
(1, 3),
(1, 4),
(1, 5),
(6, 7),
(6, 8),
(6, 9),
(6, 10),
(11, 12),
(11, 13),
(11, 14),
(11, 15)
;
WITH
Total AS
(
-- Return the number of destinations for each source.
SELECT
SourceId,
COUNT(DestinationId) AS DestinationlCount
FROM
@Sample
GROUP BY
SourceId
),
SubTotal AS
(
-- Return the number of matching destinations for each source.
SELECT
SourceId,
COUNT(DestinationId) AS DestinationlCount
FROM
@Sample
WHERE
DestinationId IN (2, 3, 4, 5, 7, 12)
GROUP BY
SourceId
)
-- Return sources where all destinations where matched.
SELECT
t.SourceId
FROM
Total AS t
INNER JOIN SubTotal AS st ON st.SourceId = t.SourceId
AND st.DestinationlCount = t.DestinationlCount
;
SourceId
1
答案 1 :(得分:0)
您可以使用以下示例代码实现此目的。我假设你把所有输入传递给你proc到一个表 -
Create table #Source (SourceId int , DestinationId int )
insert into #Source
values
(1 , 2),
(1 , 3),
(1 , 4),
(1 , 5),
(6 , 7),
(6 , 8),
(6 , 9),
(6 , 10),
(11 , 12),
(11 , 13),
(11 , 14),
(11 , 15)
Create table #Input ( DestinationId int )
insert into #Input
values (2),(3),(4),(5),(7),(12)
select t1.SourceId , count(t1.DestinationId) , count(t2.DestinationId) from #Source t1
left join #Input t2
on t1.DestinationId = t2.DestinationId
group by t1.SourceId
having count(t1.DestinationId) = count(t2.DestinationId)