Oracle 中 decode 函式用法

2022-09-21 10:12:12 字數 1719 閱讀 8187

含**釋:

decode(條件,值1,返回值1,值2,返回值2,...值n,返回值n,預設值)

該函式的含義如下:

if 條件=值1 then

return(翻譯值1)

elsif 條件=值2 then

return(翻譯值2)

......

elsif 條件=值n then

return(翻譯值n)

else

return(預設值)

end if

decode(欄位或字段的運算,值1,值2,值3)

這個函式執行的結果是,當字段或字段的運算的值等於值1時,該函式返回值2,否則返回值3

當然值1,值2,值3也可以是表示式,這個函式使得某些sql語句簡單了許多

使用方法:

1、比較大小

select decode(sign(變數1-變數2),-1,變數1,變數2) from dual; --取較小值

sign程式設計客棧()函式根據某個值是0、正數還是負數,分別返回0、1、-1

例如:變數1=10,變數2=20

則sign(變數1-變數2)返回-1,decode解碼結果為「變數1」,達到了取較小值的目的。

2、此函式用在sql語句中,功能介紹如下:

decode函式與一系列巢狀的 if-then-else語句相似。base_exp與compare1,compare2等等依次進行比較。如果base_exp和 第i 個compare項匹配,就返回第i 個對應的value 。如果bas程式設計客棧e_exp與任何的compare值都不匹配,則返回default。每個compare值順次求值,如果發現乙個匹配,則剩下的compare值(如果還有的話)就都不再求值。乙個為null的base_exp被認為和null compare值等價。如果需要的話,每乙個compare值都被轉換成和第一leiuxc個compare 值相同的資料型別,這個資料型別也是返回值的型別。

decode函式在實際開發中非常的有用

結合lpad函式,如何使主鍵的值自動加1並在前面補0

select lpad(decode(count(記錄編號),0,1,max(to_number(記錄編號)+1)),14,'0') 記錄編號 from tetdmis

eg:select decode(dir,1,0,1) from a1_interval

dir 的值是1變為0,是0則變為1

比如我要查詢某班男生和女生的數量分別是多少?

通常我們這麼寫:

select count(*) from 表 where 性別 = 男;

select count(*) from 表 where 性別 = 女;

要想顯示到一起還要union一下,太麻煩了

用decode呢,只需要一句話

select sum(decode(性別,男,1,0)),sum(decode(性別,女,1,0)) from 表

leiuxceg:

select sum(decode(siteno,'lt',1,0)),sum(decode(siteno,'sz',1,0)) from facd605;

select sum(case siteno when 'lt' then 1 else 0 end),sum(case siteno when 'sz' then 1 else 0 end) from facd605;

vinson

總結本文標題: oracle 中 decode 函式用法

本文位址:

Oracle 中 decode 函式用法

含 釋 decode 條件,值1,返回值1,值2,返回值2,值n,返回值n,預設值 該函式的含義如下 if 條件 值1 then return 翻譯值1 elsif 條件 值2 then return 翻譯值2 elsif 條件 值n then return 翻譯值n else return 預設值...

Oracle 中 decode 函式用法

含 釋 decode 條件,值1,返回值1,值2,返回值2,值n,返回值n,預設值 該函式的含義如下 if 條件 值1 then return 翻譯值1 elsif 條件 值2 then return 翻譯值2 elsif 條件 值n then return 翻譯值n else return 預設值...

Oracle 中 decode 函式用法

含 釋 decode 條件,值1,返回值1,值2,返回值2,值n,返回值n,預設值 該函式的含義如下 if 條件 值1 then return 翻譯值1 elsif 條件 值2 then return 翻譯值2 elsif 條件 值n then return 翻譯值n else return 預設值...