我有一张表格,其中包含学生的姓名,course_id和分数,不同的学生可能会有不同的课程和分数。
现在我需要输出每个学生的学术排名,这是学术排名的规则:
表格:
Student_name| course_id |score
Shirley Caws 55993 10
Lana Glendenning 56988 81
Michael 54880 80
Michael 54895 71
Sean Turle 56986 32
Sean Turle 56991 48
Sean Turle 56992 20
Damchu Tenzin 56215 40
Damchu Tenzin 56219 90
Blake Croll 57179 30
Blake Croll 57264 20
我尝试写了一个小时的案例“ CASE WHEN”,但没有得到正确的答案。 从表中选择学生名,(在...时,然后在其他情况下输入)作为学术排名;
预期结果:
Student_name| Academic_standings
Shirley Caws Referral
Lana Glendenning Good
Michael Good
Sean Turle Probation
Damchu Tenzin Referral
Blake Croll Probation
谢谢!
答案 0 :(得分:1)
我会尝试类似的事情-首先计算类别,然后应用您的逻辑:
; with CTE as (
Select StudentName
, Count(distinct CourseID) as TotalClasses
, Count(distinct case when score < 50 then CourseID end) as ClassesUnder50
From MyTable
Group By StudentName
)
Select StudentName
, Case when TotalClasses = 1 and ClassesUnder50 = 0 then 'Good'
when TotalClasses = 1 and ClassesUnder50 = 1 then 'Referral'
when TotalClasses > 1 and ClassesUnder50 = TotalClasses then 'Probation'
when TotalClasses > 1 and ClassesUnder50*1.0/TotalClasses >= 0.5 then 'Referral'
else 'Good' end as Standing
from CTE
答案 1 :(得分:0)
您可以使用聚合功能和条件聚合:
select student_name,
(case when count(*) = 1 and max(score) >= 50 then 'Good'
when count(*) = 1 then 'Referral'
when max(score) < 50 then 'Probation'
when sum(case when score >= 50 then 1 else -1 end) <= 0 then 'Referral'
else 'Good'
end) as academic_standing
from t
group by student_name;