一、 基本表達式
(case when {條件表達式} then {結果表達式}
when {條件表達式} then {結果表達式}
when {條件表達式} then {結果表達式}
else {結果表達式} end) as 字段名
要注意不要漏了else 和end
二、 用法
1. 創建一個新字段,其取值由另外一個字段的取值確定。
例如,有如下數據,需要創建一個新列“評價”,根據考試成績確定其評價結果,
成績>=90, 優秀
90>成績>=70, 良好
70>成績>=60, 及格
成績<60, 不及格
姓名 | 成績 | 評價 |
張三 | 91 | |
李四 | 80 | |
王二 | 73 | |
大哥 | 66 | |
小弟 | 52 |
SQL語法如下:
Select (case when 成績>=90 then ‘優秀’
when 成績>=70 then ‘良好’
when 成績>=60 then ‘及格’
else ’不及格‘ end) as 評價
2. 將長表數據轉化爲寬表數據
有以下表哥數據,需要將各個科目的值放到字段上去
姓名 | 科目 | 成績 |
張三 | 語文 | 91 |
張三 | 數學 | 80 |
張三 | 英語 | 73 |
張三 | 物理 | 96 |
張三 | 化學 | 52 |
形成如下格式:
姓名 | 語文 | 數學 | 英語 | 物理 | 化學 |
張三 | 91 | 80 | 73 | 96 | 52 |
SQL 語法爲:
Select sum(case when 科目=‘語文’ then 成績 else 0 end)as 語文成績,
sum(case when 科目=‘數學’ then 成績 else 0 end)as 數學成績,
sum(case when 科目=‘語文’ then 成績 else 0 end)as 英語成績,
sum(case when 科目=‘數學’ then 成績 else 0 end)as 物理成績
from table 成績表
group by 姓名;