I have a table (@ t1) that contains several sets. I want to find the perfect match for @ t2 in @ t1.
In this example, the desired result is 1.
(set 1 works well, set 2 contains three elements, while @ t2 contains only two elements, set 3 contains fewer elements than @ t2, set 4 contains NULL elements that are not allowed in @ t2, and the set 5 contains the correct number of elements, but one of the elements is not equal.)
DECLARE @t1 TABLE (id INT, data INT); DECLARE @t2 TABLE (data INT PRIMARY KEY); INSERT INTO @t1 (id, data) VALUES (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 1), (4, NULL), (4, NULL), (5, 1), (5, 3); INSERT @t2 (data) VALUES (1), (2);
I have a request that can be executed, but it looks kind of pathetic too.
WITH t1 AS ( SELECT id, data FROM @t1 WHERE data IS NOT NULL ), t1_count AS ( SELECT id, RCount = COUNT(*) FROM @t1 WHERE data IS NOT NULL GROUP BY id ) SELECT t1.id FROM t1 JOIN t1_count ON t1.id = t1_count.id FULL JOIN @t2 t2 ON t1.data = t2.data WHERE t1_count.RCount = (SELECT RCount = COUNT(*) FROM @t2) GROUP BY t1.id HAVING COUNT(t1.data) = COUNT(t2.data);
EDIT (comment by GarethD):
WITH t1 AS ( SELECT id, data, RCount = COUNT(*) OVER(PARTITION BY id) FROM @t1 WHERE data IS NOT NULL ) SELECT t1.id FROM t1 FULL JOIN @t2 t2 ON t1.data = t2.data WHERE t1.RCount = (SELECT RCount = COUNT(*) FROM @t2) GROUP BY t1.id HAVING COUNT(t1.data) = COUNT(t2.data);