简体   繁体   English

SQL Server:与列表中的所有值匹配的结果

[英]SQL Server: Result that matches all values in a list

I have two tables which are listed below. 我有下面列出的两个表。

TableA 表A

StudentID   StudentName
1           A
2           B
3           C
4           D
5           E

TableB 表B

StudentID  ClassID  SectionID
1          2        5
3          2        7

Now I am trying to retrieve those students for which all items in an input list matches. 现在,我尝试检索输入列表中所有项目都匹配的那些学生。

For example, If I pass the input list (ClassID & SectionID) as (2, 5), it should return StudentID : 1 例如,如果我将输入列表(ClassID&SectionID)传递为(2,5),则应返回StudentID:1
If I pass the input list as (2, 5 | 1, 1) it should not return the StudentID : 1 如果我将输入列表传递为(2,5 | 1,1),则不应返回StudentID:1

DECLARE @tblData AS TABLE
(
     [ClassID]      INT
    ,[SectionID]    INT

)

INSERT INTO @tblData VALUES (2, 5)
INSERT INTO @tblData VALUES (2, 1)

SELECT
     A.[StudentID]
    ,A.[StudentName]
    ,B.[ClassID]
    ,B.[SectionID]
FROM
    [AAAAAA] AS A
        INNER JOIN [BBBBBB] AS B
            ON A.[StudentID] = B.[StudentID]
        INNER JOIN @tblData AS C
            On B.[ClassID] = C.[ClassID] AND B.[SectionID] = C.[SectionID]

Unfortunately, the above mentioned query does not return the expected value. 不幸的是,上述查询未返回期望值。

Can you please help me? 你能帮我么?

We should JOIN table B with @tblData and group by StudentId . 我们应该使用@tblData JOINB @tblData StudentId分组。 Then using HAVING select all StudentID from this connection where count of rows = count of rows in @tblData . 然后使用HAVING从此连接中选择所有StudentID ,其中行数= @tblData的行数。 It means that this studentId matches ALL items in an input list 这意味着此studentId匹配输入列表中的所有项目

SELECT
     A.[StudentID]
    ,A.[StudentName]
    ,B.[ClassID]
    ,B.[SectionID]
FROM  A
     INNER JOIN B
            ON A.[StudentID] = B.[StudentID]
     INNER JOIN 
       (
          SELECT StudentID FROM @tblData
                           JOIN B ON  @tblData.ClassID=B.ClassID 
                                      AND 
                                      @tblData.SectionID=B.SectionID
          GROUP BY StudentID
          HAVING COUNT(*) = (SELECT COUNT(*) FROM @tblData)
) AS T1 on A.StudentID=T1.StudentID

SQLFiddle demo SQLFiddle演示

The point is that since you are Joining the @tblData with B, the engine matches the whole table B with @tblData. 关键是,由于您要将@tblData与B联接在一起,因此引擎会将整个表B与@tblData进行匹配。 This way, if you pass a list of input values, you will get every student that matches with one entry in @tblData. 这样,如果传递输入值列表,您将获得与@tblData中的一个条目匹配的每个学生。

To avoid this, you could insert either some where/groupby clause that matches the count of entries for one student with the count of entries in @tblData or a subquery. 为了避免这种情况,您可以插入一些where / groupby子句,该子句将一个学生的条目数与@tblData中的条目数相匹配,或者插入一个子查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM