mysql 中 case when then .... else end 的簡單使用


數據SQL CASE 表達式是一種通用的條件表達式,類似於其它語言中的 if/else 語句。 

CASE WHEN condition THEN result 

   WHEN condition THEN result 

   .............
   [WHEN ...] 
   [ELSE result] 
END 

CASE 子句可以用於任何表達式可以有效存在的地方。 condition 是一個返回boolean 的表達式。 如果結果為真,那么 CASE 表達式的結果就是符合條件的 result。 如果結果為假,那么以相同方式搜尋任何隨后的 WHEN 子句。 如果沒有 WHEN condition 為真,那么 case 表達式的結果就是在 ELSE 子句里的值。 如果省略了 ELSE 子句而且沒有匹配的條件, 結果為 NULL。

或其語法為:

簡單Case函數 
CASE sex 
         WHEN '1' THEN '男' 
         WHEN '2' THEN '女' 
ELSE '其他' END 

建議都使用第一種,少記點,也好理解。

例子:如下某學校在2005和2006年比賽的數據,

 

1)將 win_loss 中的勝,負,平 都變成 對應的 ‘win’,'loss','tie'

select date_year,
    case 
    when win_loss='' then 'win'
    when win_loss='' then 'loss' 
    else 'tie' 
    end win_loss
    from scores;

2) 假設勝得3分,平得一分,負得0分,統計每一年的得分

select date_year ,
sum(case when win_loss='' then 3 when win_loss='' then 1 else 0 end ) score 
from scores group by date_year;

3)統計每一年的 勝場數,平場數 和 負場數

select date_year ,
sum(case when win_loss='' then 1 else 0 end ) '勝場數' ,
sum(case when win_loss='' then 1 else 0 end) '負場數',
sum(case when win_loss='' then 1 else 0 end) '平場數' 
from scores group by date_year;

由例一可以發現,使用 case when  then  else then 時 是每一條語句都去執行一遍。

例二:數據集如下:

 

試試看:

select tname, case when ttype = '語文' then tscor else 0 end from testScore

1)用一行來顯示一個學生的成績

select tname, tscor
from testScore group by tname;

select tname, 
(case when ttype='語文' then tscor else 0 end) '語文', 
(case when ttype ='數學' then tscor else 0 end) '數學', 
(case when ttype ='英語' then tscor else 0 end) '英語'
from testScore group by tname;

select
    tname as '姓名' ,     
    max(case ttype when '語文' then tscor else 0 end) '語文',     
    max(case ttype when '數學' then tscor else 0 end) '數學',     
    max(case ttype when '英語' then tscor else 0 end) '英語'     
from testScore     
group by tname;
select tname, 
max(case  when ttype='語文' then tscor else 0 end) '語文', 
max(case when ttype ='數學' then tscor else 0 end) '數學', 
max(case when ttype ='英語' then tscor else 0 end) '英語'
from testScore group by tname;

這兩是是同樣的結果。

對比上面,聚和函數的作用。。。。??

 2)統計學生文科,理科的總分。

select tname as '姓名',
       case
        when ttype='數學' then '理科' else '文科' end as '科別',
        sum(tscor) as '總分'
    from testScore
    group by tname,
             case 
             when ttype='數學' then '理科' else '文科' end ;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM