我想将一个表(独占)从表中匹配到另一个表,并且只返回与ALL匹配的行。这是我的例子:
DECLARE @T1 TABLE (Gr int, Dim char(1), Val int)
INSERT INTO @T1 VALUES (1,'A',10)
INSERT INTO @T1 VALUES (1,'B',200)
INSERT INTO @T1 VALUES (1,'B',201)
INSERT INTO @T1 VALUES (1,'B',202)
INSERT INTO @T1 VALUES (1,'C',22)
INSERT INTO @T1 VALUES (1,'C',23)
INSERT INTO @T1 VALUES (1,'C',24)
DECLARE @T2 TABLE (eDim char(1), eVal int)
INSERT INTO @T2 VALUES ('B', 200)
INSERT INTO @T2 VALUES ('C', 29)
SELECT T1.Gr, T1.Dim, T1.Val FROM @T1 T1
WHERE EXISTS (SELECT * FROM @T2 T2 WHERE T2.eDim = T1.Dim AND T2.eVal = T1.Val)
在上面的示例中,查询从T1返回对应于B-200值对的一行。我真正需要的是当B和C值都匹配T2时返回两个记录,或者如果一个或多个记录不匹配则不返回任何记录。类似于“WHERE EXISTS ALL”之类的东西,但SQL SERVER无法识别。
答案 0 :(得分:0)
一个人去做
SELECT Gr, eDim Dim, eVal Val
FROM
(
SELECT T1.Gr
FROM @T1 t1 JOIN @T2 t2
ON t1.dim = t2.edim
AND t1.val = t2.eval
GROUP BY t1.gr
HAVING COUNT(*) =
(
SELECT COUNT(*) FROM @T2
)
) q CROSS JOIN @T2
以下是 SQLFiddle 演示尝试取消注释上一个INSERT INTO @T1
并再次运行查询
或
SELECT gr, dim, val
FROM
(
SELECT gr, dim, val, COUNT(*) OVER (PARTITION BY gr) cnt
FROM @T1 t1 JOIN @T2 t2
ON t1.dim = t2.edim
AND t1.val = t2.eval
GROUP BY gr, dim, val
) q
WHERE cnt =
(
SELECT COUNT(*) FROM @T2
)
以下是 SQLFiddle 演示尝试取消注释上一个INSERT INTO @T1
并再次运行查询