如何在此查询中显示某些值? SQL

时间:2015-03-30 23:09:10

标签: sql sql-server

这是我当前的查询:

SELECT DISTINCT 
    grade, SNAME
FROM  
    Grade_report 
JOIN 
    Student ON Grade_report.student_number = Student.stno
WHERE 
    grade LIKE '[a-b]'

我需要显示已收到多个A或B的学生。我应该添加什么?

1 个答案:

答案 0 :(得分:0)

我刚刚在这里创建了一些示例数据,但您的答案需要HAVING关键字。

https://msdn.microsoft.com/en-us/library/ms180199.aspx

在这种情况下,约翰是唯一的结果,因为他同时收到了A和B.

DECLARE @temptable AS TABLE 
            (CLASS int PRIMARY KEY IDENTITY,
            SNAME varchar(20),
            GRADE char(1));

        INSERT INTO @temptable(SNAME,GRADE)
        VALUES ('John','A'),('Jack','B'),('John','B'),('Jack','C'),('Jill','D');


        SELECT * FROM @temptable

        --This is your answer
        SELECT SNAME,COUNT(*)
        FROM @temptable
        WHERE GRADE IN ('A','B')
        GROUP BY SNAME
        HAVING COUNT(*)>1