oracle sql文字列函数,Oracle 数据库SQL中 decode()函数简介
decode()函數簡介:
主要作用:將查詢結果翻譯成其他值(即以其他形式表現出來,以下舉例說明);
使用方法:
Select decode(columnname,值1,翻譯值1,值2,翻譯值2,...值n,翻譯值n,缺省值)
From talbename
Where …
其中columnname為要選擇的table中所定義的column,
·含義解釋:
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
注:其中缺省值可以是你要選擇的column name 本身,也可以是你想定義的其他值,比如Other等;
舉例說明:
現定義一table名為output,其中定義兩個column分別為monthid(var型)和sale(number型),若sale值=1000時翻譯為D,=2000時翻譯為C,=3000時翻譯為B,=4000時翻譯為A,如是其他值則翻譯為Other;
SQL如下:
Select monthid , decode (sale,1000,'D',2000,'C',3000,'B',4000,'A',’Other’) sale from output
特殊情況:
若只與一個值進行比較
Select monthid ,decode(sale, NULL,‘---’,sale) sale from output
另:decode中可使用其他函數,如nvl函數或sign()函數等;
NVL(EXPR1,EXPR2)
若EXPR1是NULL,則返回EXPR2,否則返回EXPR1.
SELECT NAME,NVL(TO_CHAR(COMM),'NOT APPLICATION') FROM TABLE1;
如果用到decode函數中就是
select monthid,decode(nvl(sale,6000),6000,'NG','OK') from output
sign()函數根據某個值是0、正數還是負數,分別返回0、1、-1,
如果取較小值就是
select monthid,decode(sign(sale-6000),-1,sale,6000) from output,即達到取較小值的目的。
1.1.1.1?行轉列,并匯總求和
Oracle數據庫中,行轉列可以使用到decode函數進行處理。
例如表t1有以下數據
合同號(hth)
科目(kmbh)
金額(je)
發生日期
00001
01
20
2015-01-02
00001
02
30
2015-01-02
00002
01
25
2015-01-02
00001
01
15
2015-01-03
00002
02
40
2015-01-03
00001
03
50
2015-01-04
現需要將以上數據匯總,合同下相同科目的金額匯總到一起,并將科目按列展示
合同號
科目01
科目02
科目03
00001
35
20
50
00002
25
40
0
可使用以下SQL實現:
select hth,sum(decode(kmbh,’01’,je,0))
科目01,?sum(decode(kmbh,’02’,je,0)) 科目02,?sum(decode(kmbh,’03’,je,0)) 科目03?from t1 group by hth
總結
以上是生活随笔為你收集整理的oracle sql文字列函数,Oracle 数据库SQL中 decode()函数简介的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux撤销删除命令(linux撤销删
- 下一篇: mysql typeindex_expl