基于不同条件的学生成绩

时间:2017-03-16 05:40:59

标签: sql-server sql-server-2008 tsql

enter image description here

大家好,

我有不同科目的学生分数。

表#Maths包含名为a,b和c的学生数学中的标记。 类似于#Science和#English。

现在我想要输出,好像学生在两个科目中有超过75分,他将被评为成绩' Merit'。如果他在一个科目中超过75分而在其他科目中超过60分等级将是' Pass'如果一个主题没有超过75且一个主题少于50,那么他将被评为“失败”?

请为我提供结果的解决方案?

由于

2 个答案:

答案 0 :(得分:1)

Passwords

不是很优雅,但由于只需要比较几列,我就这样接近

答案 1 :(得分:1)

您可以尝试以下查询:

  • 此查询肯定比Joins快,因为它减少了案例条件的操作集
  • 业务逻辑被整齐地封装为权重和最高查询条件的一部分
  • 没有加入,因此更快。当您开始增加学生记录和主题表时,速度将变得明显。

查询:

select 
  id, 
  name, 
  case 
       when sum(weightRank) >=32 then "Merit"
       when sum(weightRank) >=20 then "Pass"
       when sum(weightRank) <16 and  count(ALL weightRank) < count(weightRank)    
       then "Fail"
       else "N/A"
  end as grade
from
 (
    select id,name,'m' as subject,marks from #maths
        union all 
    select id,name,'m' as subject,marks from #science
        union all
    select id,name,'m' as subject,marks from #english 
) allmarks

-- allmarks get all records together, and is faster than joining all tables
-- this is also extensible as subjects and students may increase
-- and not all subjects may have marks for all students, so we will not lose data as in case of joins

    join 
        (values (NULL,0, 50),(1,51, 60),(4,61, 75), (16,76,100) 
        as I(weightRank,lowNumber, highNumber)

-- here we create a temp dynamic table to weight the marks 

        on 
            allmarks.marks between I.lowNumber AND I.HighNumber

group by id,name