计算失败等级SQL的数量

时间:2018-05-22 15:02:06

标签: sql sql-server

我需要找到成绩最差的前5名学生。所以我必须计算每个PERSON_ID的失败成绩的数量,然后我需要按每个PERSON_ID的失败成绩数量排序,然后排在前面

使用此语句,所有表都会加入,只显示成绩不合格的学生。现在我只需计算每个PERSON_ID的失败成绩数,然后再订购。

当我这样做时,我不断收到语法错误。希望有人可以帮助我。

2 个答案:

答案 0 :(得分:0)

可能你可以使用下面的查询。 当我不了解有关列/架构/数据的更多信息时,我会特别小心加入计数

Select 
TOP 5
    students.PERSON_ID, 
    NumberOfGradesFailed=COUNT(1) 
from students 
    inner join grades 
        on students.PERSON_ID = grades.PERSON_ID 
    inner join grade_types 
        on grades.Grade = grade_types.Grade
where PASSING_GRADE = 0
group by students.PERSON_ID 
ORDER BY 2 DESC

答案 1 :(得分:0)

您需要将person_id限定为students.person_id,因为您在多个表中有该列

select top 5 * from (
Select students.person_id, enroll_period, count(*) cnt from students 
inner join grades on students.PERSON_ID = grades.PERSON_ID 
inner join grade_types on grades.Grade = grade_types.Grade
Where PASSING_GRADE = 0
group by students.person_id, enroll_period)a
order by cnt desc