使用带有搜索CASE表达式的SELECT语句

时间:2014-02-09 12:33:08

标签: mysql sql database

我创建了一个表scores,如下所示。

student_id course score
1 math 90
1 cs 70
2 math 60
2 cs 50

我想按比例对学生的所有分数进行分类:

>60 pass
<60 fail
=60 bottomline

然后,我写了一个带有case表达式为

的select语句
select student_id, course, score =
(case score    
     when score > 60
     then 'pass'
     when score < 60
     then 'fail'
     else 'bottomline'
end) as 'result'
from scores
order by student_id

但是,结果集如下所示,result列未将类别显示为pass, 根据比例,failbottomline。相反,所有result值均为0

student_id course result
1 math 0
1 cs 0
2 math 0
2 cs 0

导致所有result值为0的select语句出错了吗?我正在使用MySQL数据库服务器。

4 个答案:

答案 0 :(得分:2)

为什么score = ...

只是:

select student_id, course, score, 
(case score    
     when score > 60
     then 'pass'
     when score < 60
     then 'fail'
     else 'bottomline'
end) as 'result'
from scores
order by student_id

答案 1 :(得分:1)

select student_id, course, score,
   case                        --<-- you dont need to mention column name here
     when score < 60  then 'fail'
     when score = 60  then  'bottomline' 
     when score > 60  then 'pass'
   end as 'result'
from scores
order by student_id

Sql Fiddle

答案 2 :(得分:0)

试试这个

SLELECT student_id, course,Score
   CASE  
     when score < 60  then 'fail'
     when score > 60  then 'pass'
   Else 'bottomline'
   END 'result'
FROM scores
ORDER BY student_id

答案 3 :(得分:0)

Try This 
Create table scores (student_id int,course VARCHAR(100),score int);
Insert into scores values(1,'math',90);
Insert into scores values(1,'cs',70);
Insert into scores values(2,'math',60);
Insert into scores values(2,'cs',50);

Select student_id, course,score,
(case     
     when score > 60
     then 'pass'
     when score < 60
     then 'fail'
     else 'bottomline'
end) as 'result'
from scores
order by student_id;