如何输出一个值引用另一个值?

时间:2019-04-17 16:50:24

标签: sql sql-server

我有一张表格,其中包含学生的姓名,course_id和分数,不同的学生可能会有不同的课程和分数。

现在我需要输出每个学生的学术排名,这是学术排名的规则:

  1. 如果学生仅修一门课程(count(course_id)= 1),则如果得分> = 50,他/她将获得“好”;如果得分<50,他/她将获得“推荐”;
  2. 如果学生修读多门课程(count(course_id)> = 2),则如果其得分均不大于50,则他/她的学业成绩将为“试用”,如果不超过50%,则其“推荐”所修课程的得分> = 50,否则为“好”。

表格:

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

谢谢!

2 个答案:

答案 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;