1. 程式人生 > >SQL CASE 的用法

SQL CASE 的用法

sql case 的用法

  1. --簡單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

-------------------------------------------------------------------------------------------------------------------


2.批量更新數據

--假設狀態只有3個選項,把所有FStatus=3的更新為1,FStatus=88的更新為5,FStatus=99的更新為9,

update T_SUF_Barcode set FStatus=(case FStatus

when ‘3‘ then ‘1‘

when ‘88‘ then ‘55‘

else FStatus end)

where FBarcode between ‘180121702150001‘ and ‘180121702153000‘

----------------------------------------------------------------------------------------------------------------


3.將條碼表中的狀態用中文表示


select fstatus from T_SUF_Barcode t1 where FBarcode between ‘180121702150001‘ and ‘180121702153000‘

--------------------------------------------------------------------------------------------------------------------

fstatus

1

...

5

...

5

9

...

---------------------------------------------------------------------------------------------------------------------


select t1.FBarcode, (case t1.FStatus

when 1 then ‘正常‘

when 5 then ‘未知‘

when 9 then ‘作廢‘ end)狀態

from T_SUF_Barcode t1

where FBarcode between ‘180121702150001‘ and ‘180121702153000‘


FBarcode狀態

180121702150001正常

180121702150002...

180121702150003 未知

180121702150004...

180121702150011作廢

180121702150012...




4.將sum與case結合使用,可以實現分段統計。
如果現在希望將上表中各種狀態的條碼進行統計,sql語句如下:


select

sum(case t1.FStatus when 1 then 1 end)正常,

sum(case t1.FStatus when 5 then 2 end)未知,

sum(case when t1.FStatus !=1 and t1.FStatus!=5 then 1 end)作廢

from T_SUF_Barcode t1 where FBarcode between ‘180121702150001‘ and ‘180121702153000‘


--sum求和,當為5時,更新為2,並求和符合條件的2。這裏正常,未知,作廢符合條件的各有1000個數據。


正常 未知 作廢

1000 2000(1000*2) 1000


--------------------------------------------

select

count(case t1.FStatus when 1 then 1 end)正常,

count(case t1.FStatus when 5 then 1 end)未知,

count(case when t1.FStatus !=1 and t1.FStatus!=5 then 1 end)作廢

from T_SUF_Barcode t1 where FBarcode between ‘180121702150001‘ and ‘180121702153000‘


--統計符合條件的個數。


正常 未知 作廢

1000 1000 1000


SQL CASE 的用法