SQL CASE 多條件用法

2021-10-05 12:28:13 字數 2328 閱讀 4356

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

--簡單case函式

case ***

when'1'then'男'

when'2'then'女'

else'其他'end

--case搜尋函式

case when *** ='1'then'男'

when *** ='2'then'女'

else'其他'end

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

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

--比如說,下面這段sql,你永遠無法得到「第二類」這個結果

例子: case 說明 1.長期 2.有效期內 3.預上線 4.下線

select ad.*,

( case when ad.status="online" and ad.begin_at=0 and ad.end_at=0 then "1"

when ad.status="online" and ad.begin_atand ad.end_at>unix_timestamp()*1000 then "1" 

when ad.status="online" and ad.begin_at>unix_timestamp()*1000 and ad.end_at>unix_timestamp()*1000 then "1" 

when ad.status="offline" then "2" else "2" end ) statustime 

from `advertisement`

例子:按照case條件查詢

select * from

( select ad.*,

( case 

when ad.status="online" and ad.begin_at=0 and ad.end_at=0 then "1" 

when ad.status="online" and ad.begin_atunix_timestamp()*1000 then "1" 

when ad.status="online" and ad.begin_at>unix_timestamp()*1000 and ad.end_at>unix_timestamp()*1000 then "1" 

when ad.status="offline" then "2" else "2" end ) statustime 

from `advertisement` as ad ) as adnew

where statustime=1;

連表case 作為條件查詢

case 說明 1.長期 2.有效期內 3.預上線 4.下線

select * from ( select ad.*, adv.adv_id,

( case 

when ad.status="online" and ad.begin_at=0 and ad.end_at=0 then "1" 

when ad.status="online" and ad.begin_atunix_timestamp()*1000 then "1" 

when ad.status="online" and ad.begin_at>unix_timestamp()*1000 and ad.end_at>unix_timestamp()*1000 then "1" 

when ad.status="offline" then "2" else "2" end ) statustime 

from `advertisement` as ad 

right join `adv_web` as adv on adv.adv_id = ad.id ) as adnew where statustime=1;

SQL CASE 多條件用法

case具有兩種格式。簡單case函式和case搜尋函式。簡單case函式 case when 1 then 男 when 2 then 女 else 其他 end case搜尋函式 case when 1 then 男 when 2 then 女 else 其他 end 這兩種方式,可以實現相同的...

sql case 用法總結

快下班了,抽點時間總結一下sql 的 case 用法。sql 裡的case的作用 用於計算條件列表的表示式,並返回可能的結果之一。sql 的case 型別於程式語言裡的 if esle if else 或者 switch,但它不用於控制sql程式的執行流程,而是作為列的邏輯使用。語法 case in...

多條件查詢

思路 1.獲取引數值 2.生成查詢條件 3.獲取查詢結果 4.繫結查詢選項 呼叫geturlhtml方法生成查詢url 例如 var y2013 pnvshihufu qbeijing sxuhuiqu 得到url變數值 protected string geturlval string name ...