SQL學習筆記——case表達式

語法:

select <列名>,
case when <求值表達式> then <表達式>
     when <求值表達式> then <表達式>
     when <求值表達式> then <表達式>
     .. .
     else <表達式>
end
from <表名>

when 子句中的“< 求值表達式>”就是類似“列 = 值”這樣,返回值爲真值。case 表達式會從對最初的when子句中的“< 求值表達式>”進行求值開始執行。如果結果爲真(true),那麼就返回then子句中的表達式,該條case表達式的執行到此爲止,繼續執行下一條。如果結果不爲真,那麼就跳轉到下一條when子句的求值之中。如果直到最後的when子句爲止返回結果都不爲真,那麼就會返回else
中的表達式,執行終止。

else子句也可以省略不寫,這時會被默認爲else null。此外,case表達式最後的“end”是不能省略的。

--搜索型case表達式
select product_name,
       case product_type
            when '衣服' then concat('A :' , product_type)
            when '辦公用品' then concat('B :' , product_type)
            when '廚房用具' then concat('C :' , product_type)
            else null
       end as abc_product_type
from product;

--簡單型case表達式
select product_name,
       case when product_type = '衣服' then concat('A :' , product_type)
            when product_type = '辦公用品' then concat('B :' , product_type)
            when product_type = '廚房用具' then concat('C :' , product_type)
            else null
       end as abc_product_type
from product;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章