2017-05-15 61 views
-1

我無法構建SQL以獲取所需的輸出。針對以下要求的SQL

表X

Id_X | GroupId | SomeColumn 

表ř

Id_R | Id_X | GroupId | RColumn 

的目的是從表ř挑Id_X僅具有的GroupId值(A,B)和RColumn值是右值

例如:

表X

1 | A | SomeValue 
1 | B | SomeValue 
2 | A | SomeValue 
2 | B | SomeValue 
2 | B | SomeValue 
2 | C | SomeValue 

表[R

101 | 1 | A | RValue 
102 | 2 | A | RValue 

的SQL應該返回1

回答

0

如果我理解正確的,您的查詢應該是

DECLARE @TableX AS TABLE 
(
    Id_X int, GroupId varchar(10), SomeColumn varchar(20) 
) 

INSERT INTO @TableX 
VALUES 
(1, 'A', 'SomeValue'), 
(1, 'B', 'SomeValue'), 
(2, 'A', 'SomeValue'), 
(2, 'B', 'SomeValue'), 
(2, 'B', 'SomeValue'), 
(2, 'C', 'SomeValue') 

DECLARE @TableR AS TABLE 
(
    ID_R int, Id_X int, GroupId varchar(10),RColumn varchar(10) 
) 

INSERT INTO @TableR 
VALUES (101,1,'A','RValue'), (102,2,'A','RValue') 

SELECT DISTINCT tr.Id_X 
FROM  @TableR tr 
     INNER JOIN @TableX tx ON tx.Id_X = tr.Id_X AND tx.GroupId = tr.GroupId 
WHERE tr.RColumn = 'RValue' 
AND NOT EXISTS ( SELECT 1 FROM @TableX tx2 
        WHERE tx2.Id_X = tx.Id_X 
         AND tx2.GroupId NOT IN ('A','B') 
       ) 

演示鏈接:http://rextester.com/EGLOT75874