mysql if--else


SQL之case when then用法

case具有兩種格式。簡單case函數和case搜索函數。

復制代碼
--簡單case函數
case sex
  when '1' then '男'
  when '2' then '女’
  else '其他' end
--case搜索函數
case when sex = '1' then '男'
     when sex = '2' then '女'
     else '其他' end  
復制代碼

這兩種方式,可以實現相同的功能。簡單case函數的寫法相對比較簡潔,但是和case搜索函數相比,功能方面會有些限制,比如寫判定式。

 

還有一個需要注重的問題,case函數只返回第一個符合條件的值,剩下的case部分將會被自動忽略。

--比如說,下面這段sql,你永遠無法得到“第二類”這個結果
case when col_1 in ('a','b') then '第一類'
     when col_1 in ('a') then '第二類'
     else '其他' end  

下面實例演示:

3、將sum與case結合使用,可以實現分段統計。
     如果現在希望將上表中各種性別的人數進行統計,sql語句如下:

復制代碼
SQL> select
  2    sum(case u.sex when 1 then 1 else 0 end)男性,
  3    sum(case u.sex when 2 then 1 else 0 end)女性,
  4    sum(case when u.sex <>1 and u.sex<>2 then 1 else 0 end)性別為空
  5  from users u;
 
        男性         女性       性別為空
---------- ---------- ----------
         3          2          0

--------------------------------------------------------------------------------
SQL> select
  2    count(case when u.sex=1 then 1 end)男性,
  3    count(case when u.sex=2 then 1 end)女,
  4    count(case when u.sex <>1 and u.sex<>2 then 1 end)性別為空
  5  from users u;
 
        男性          女       性別為空
---------- ---------- ----------
         3          2          0
復制代碼

 


免責聲明!

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



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