TSQL如何根据多行的值计算考试结果

TSQL How to calculate exam result based on values from multiple rows

我需要根据存储在不同行中的每个科目的分数来计算学生的考试成绩。请参阅下面的标记 table。

我期待这样的结果

我尝试的查询太长且条件太多。请有人帮助我如何使用简单的 TSQL 实现此目的。

如果“based on marks”的意思是“基于是否达到某个阈值”,这样的查询将对您有所帮助。

假设 SID 在总分等于或大于 123 时通过了考试

select sid, 
       case when sum(marks) < 123 then -- replace 123 with the threshold value
         'Failed'
       else
         'Passed'
       end result
  from test_table
 group by sid

here 是 fiddle 要使用的数据库

如您所述基于每个科目的分数。

表示如果任何学生在任何科目中的分数较低,则该学生将被视为不及格。

;with test_table(sid, sub, marks) as (
  select 23, 'English', 35 union all
  select 23, 'Maths', 40 union all
  select 23, 'Science', 20 union all
  select 24, 'English', 60 union all
  select 24, 'Maths', 50 union all
  select 24, 'Science', 66
),
final_result as (
select sid, sub, case when marks < 33 then -1 else 0 end result 
from test_table 
)
select final_result.sid,  case when sum(final_result.result) < 0 then 'Failed' else 'Passed' end FinalResult 
from final_result
group by final_result.sid

如果每个科目都有最低分数标准,请使用 CASE 表达式进行检查。然后使用另一个 CASE 表达式来检查是否没有。通过标准与总人数匹配

查询

declare @minMark as int = 35; -- change accordingly

select [sid],
case when (
    sum(case when [marks] >= @minMark then 1 else 0 end) = count(*)
) then 'Pass' else 'Fail' end as [stat]
from [your_table_name]
group by [sid];