如何选择TOP 5但排除一些结果(SQL Server)

时间:2015-04-18 12:30:14

标签: sql sql-server database

所以我有这个代码..

SELECT TOP 5 Student_ID,
CASE
    WHEN SUM(Grade)/5 >= 96.5 THEN '4.0'
    WHEN SUM(Grade)/5 > 92.4 THEN '3.5'
    WHEN SUM(Grade)/5 > 88.4 THEN '3.0'
    WHEN SUM(Grade)/5 > 84.4 THEN '2.5'
    WHEN SUM(Grade)/5 > 79.4 THEN '2.0'
    WHEN SUM(Grade)/5 > 74.4 THEN '1.5'
    WHEN SUM(Grade)/5 > 69.4 THEN '1.0'
    WHEN SUM(Grade)/5 < 69.5 THEN 'R'
ELSE ''
END AS 'GPA'
FROM Grades
GROUP BY Student_ID
ORDER BY GPA DESC

结果如下:

Student_ID | GPA   
 200128       R
 200122      3.5
 200126      3.5
 200120      3.0
 200125      3.0

如何在获得TOP 5时将GPA'R'排除在学生之外?

3 个答案:

答案 0 :(得分:4)

更改order by

ORDER BY (case when GPA = 'R' then 2 else 1 end),
         GPA DESC

你也可以这样做:

ORDER BY SUM(Grade)/5 DESC

这是微妙的不同,因为第一种方式将对所有学生用相同的&#34; GPA&#34;平等的。这将按照数值对它们(在封面下)进行排序。

答案 1 :(得分:0)

添加一个having子句:

GROUP BY Student_ID
HAVING SUM(Grade) <> 'R' --Or some other criteria
ORDER BY GPA DESC

答案 2 :(得分:0)

SELECT TOP 5 Student_ID,
CASE
    WHEN SUM(Grade)/5 >= 96.5 THEN '4.0'
    WHEN SUM(Grade)/5 > 92.4 THEN '3.5'
    WHEN SUM(Grade)/5 > 88.4 THEN '3.0'
    WHEN SUM(Grade)/5 > 84.4 THEN '2.5'
    WHEN SUM(Grade)/5 > 79.4 THEN '2.0'
    WHEN SUM(Grade)/5 > 74.4 THEN '1.5'
    WHEN SUM(Grade)/5 > 69.4 THEN '1.0'
    WHEN SUM(Grade)/5 < 69.5 THEN 'R'
ELSE ''
END AS 'GPA'
FROM Grades
GROUP BY Student_ID
HAVING SUM(Grade)/5 >= 69.5
ORDER BY GPA DESC