2014-02-09 77 views
2

我創建了一個表scores,如下所示。使用帶有搜索的CASE表達式的SELECT語句

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

我想通過規模來分類一個學生的所有得分:

>60 pass 
<60 fail 
=60 bottomline 

於是,我寫了一個select語句用CASE表達式作爲

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 

哪裏是我錯引起的一切result0 select語句?我正在使用MySQL數據庫服務器。

+0

(?是什麼原因導致這個問題)我用了一個簡單的語法案例表達ssion和搜索的案例表達。在我的情況下,我應該使用搜索的表達式而不是簡單的表達式。有關案例表達式的更多信息可以在這裏找到:[link](http://technet.microsoft.com/en-us/library/ms181765.aspx) –

回答

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

+0

在查詢結果中也包括'score' –

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 
+0

您的修改顯示了所有'結果'值到'bottomline'。 –

+0

不會''bottomline'不會顯示。但所有分數都不合格<= 60' –

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