根据分数得分

时间:2015-08-04 07:42:33

标签: sql sql-server-2008

name    score
a       Pass 
a       Merit 
a       Fail 
b       Merit 
b       Merit 
b       Merit 
c       Pass 
c       Pass 
c       Pass 
d       Fail 
d       Fail 
d       Fail 

我有两栏学生名和他们的分数。 我努力尝试但无法通过它。 如果学生有两个优点,他将被授予优点。 如果学生有两次通过,他将被授予通行证 否则就是失败 所以输出就像这样

name     score
a        fail
b        merit
c        pass
d        fail

2 个答案:

答案 0 :(得分:2)

您可以按(name)创建一组行。然后,您可以计算每个组的不同类型的分数:

select  name
,       case
        when count(case when score = 'merit' then 1 end) >= 2 then 'merit'
        when count(case when score = 'pass' then 1 end) >= 2 then 'pass'
        else 'fail'
        end
from    YourTable
group by
        name

See it working at SQL Fiddle.

答案 1 :(得分:0)

一点点"更公平"恕我直言将适用以下内容:

select  name, count(case when score = 'merit' then 1 end) merits,
        count(case when score = 'pass' then 1 end) passes,
        count(case when score in ('merit','pass') then 1 end) meritsORpasses,
        case
         when count(case when score = 'merit' then 1 end) >= 2 then 'merit'
         when count(case when score in ('merit','pass') then 1 end) >= 2 then 'pass'
         else 'fail'
        end decision
from    tbl group by name

有了这个结果:

name    merits  passes  meritsORpasses  decision
a       1       1       2               pass
b       3       0       3               merit
c       0       3       3               pass
d       0       0       0               fail

您当然可以省略merits, passesmeritsORpasses列。我只是把它们放进去说明。

使用Andomar的小提琴,这里是working version