decode and nvl and sign
http://blog.sina.com.cn/s/blog_56146dc50100cnp9.html
Oracle中Decode()、nvl(),sign()函數使用技巧
decode()函數使用技巧
·軟件環(huán)境:
1、Windows NT4.0+ORACLE 8.0.4
2、ORACLE安裝路徑為:C:\ORANT
·含義解釋:
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
·? ? ? ? 使用方法:
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、表、視圖結構轉化
現有一個商品銷售表sale,表結構為:
month char(6) --月份
sell number(10,2) --月銷售金額
現有數據為:
200001 1000
200002 1100
200003 1200
200004 1300
200005 1400
200006 1500
200007 1600
200101 1100
200202 1200
200301 1300
想要轉化為以下結構的數據:
year char(4) --年份
month1 number(10,2) --1月銷售金額
month2 number(10,2) --2月銷售金額
month3 number(10,2) --3月銷售金額
month4 number(10,2) --4月銷售金額
month5 number(10,2) --5月銷售金額
month6 number(10,2) --6月銷售金額
month7 number(10,2) --7月銷售金額
month8 number(10,2) --8月銷售金額
month9 number(10,2) --9月銷售金額
month10 number(10,2) --10月銷售金額
month11 number(10,2) --11月銷售金額
month12 number(10,2) --12月銷售金額
結構轉化的SQL語句為:
create or replace view
v_sale(year,month1,month2,month3,month4,month5,month6,month7,month8,month9,month10,month11,month12)
as
select
substrb(month,1,4),
sum(decode(substrb(month,5,2),'01',sell,0)),
sum(decode(substrb(month,5,2),'02',sell,0)),
sum(decode(substrb(month,5,2),'03',sell,0)),
sum(decode(substrb(month,5,2),'04',sell,0)),
sum(decode(substrb(month,5,2),'05',sell,0)),
sum(decode(substrb(month,5,2),'06',sell,0)),
sum(decode(substrb(month,5,2),'07',sell,0)),
sum(decode(substrb(month,5,2),'08',sell,0)),
sum(decode(substrb(month,5,2),'09',sell,0)),
sum(decode(substrb(month,5,2),'10',sell,0)),
sum(decode(substrb(month,5,2),'11',sell,0)),
sum(decode(substrb(month,5,2),'12',sell,0))
from sale
group by substrb(month,1,4);
?
nvl()函數使用說明:
NVL(expr1,expr2)
如果expr1是NULL,則返回expr2,否則返回expr1.返回值與expr1類型相同,除非expr1是字符串類,在這種情況下將返回VARCHAR2類型.這個函數用于確保查詢記錄集中不包含NULL值.
類似的還有
NVL(expr1,expr2,expr3)
如果expr1是NULL,則返回expr2,否則返回expr3.返回值與expr2類型相同,除非expr2是字符類型,在這種情況下返回VARCHAR2類型
?
?
select group_no, group_desc, nvl(sum(tot_fee), 0) tot_fee
from (
?????? select distinct group_no, group_desc, user_no
????????? from dw.dw_v_user_mobileuser
????????? where tele_type in('11','12')
?????????? and if_valid='1'
?????????? and is_test='0'
?????????? and group_no in (select group_desc from bonc.dan_group_income)
?????????? and acct_month = '200902') t1,
???????
?????? (select user_no, tot_fee
????????? from dw.dw_v_user_charge_sec_h
???????? where acct_month = '200902') t2
where t1.user_no = t2.user_no(+)
group by group_no, group_desc
?
SIGN(nExpression)
當指定數值表達式的值為正、負或 0 時,分別返回 1、-1 或 0。
語法
SIGN(nExpression)
參數
nExpression
指定用 sign( ) 函數進行求值的數值表達式。如果求出值是正數,則 sign( ) 函數返回 1;如果求出值是負數,返回 -1;如果求出值為 0,則返回 0。
返回值類型
數值型
總結
以上是生活随笔為你收集整理的decode and nvl and sign的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Spring JDBC进行数据访问
- 下一篇: SAML简介:安全地共享数字身份信息