1. 程式人生 > >SQL基本函式學習筆記(order by decode)

SQL基本函式學習筆記(order by decode)

四、LPAD與RPAD的用法: 比較:select LPAD('WhaT is tHis',5),LPAD('WhaT is tHis',25),LPAD('WhaT is tHis',25,'-') from dual;             |WhaT|               WhaT is tHis| -------------WhaT is tHis      select RPAD('WhaT is tHis',5),RPAD('WhaT is tHis',25),RPAD('WhaT is tHis',25,'-') from dual;             |WhaT|  WhaT is tHis             | WhaT is tHis-------------
作用:作為調整格式的輸出,例:

with x as

( select 'aa' chr from dual

union all

select 'bb' chr from dual)

select level ,chr,lpad( ' ' ,( level - 1 )* 5 , '-' )||chr other from x connect by level <= 3

說明:若LPAD對空字串操作無效,因此至少必須有' '空格符!

LPAD的實際應用:

select distinct lpad(selltype, 2 , '0' ) from lccont;

由於系統中其他的selltype欄位均為01、02等2位,但出現7,另有null值
所以使用 lpad(selltype,2,'0') 可以即儲存null值又將7更新為07

五、rank() order by()和row_number() order by()的區別:

with t as (

select 1 a from dual

union all

select 2 a from dual

union all

select 1 a from dual

)

select a,rank() over( order by a) rank,row_number() over( order by a) num from t;

 

六、translate和replace的區別:

select translate('What is this','ait','-*%') from dual;---Wh-% *s %h*s

selectreplace('What is this','ait','-*%') from dual;-----What is this

selectreplace('What is this','hat','-*%') from dual;-----W-*% is this

translate的實際應用:

select translate('12XXX5869XXXX','0123456789'||'12XXX5869XXXX','0123456789')from dual;

<取字串中的所有數字>

七、sysdate與current_date的差別:

select sysdate,current_date from dual;

某些情況下current_date會比sysdate快一秒。

我們認為current_date是將current_timestamp中毫秒四捨五入後的返回

雖然沒有找到文件支援,但是想來應該八九不離十。

八、一些有用的時間函式:

select NEXT_DAY(sysdate,5) from dual;--下一個星期四(不算今天)

select NEXT_DAY(sysdate,'星期三') from dual;--下一個星期一(大小寫都可)

select LAST_DAY(sysdate) from dual;--當月最後一天

九、一些有用的數字/字元函式:

select GREATEST(a,b) Greatest from t2;----------求最大值

select LEAST(a,b) LEAST from t2;-------------求最小值

select NULLIF('a','b'),NULLIF('a','a') from dual;-------a=b則返回null;a<>b則返回a

select nvl(null,'a'),nvl('1','a') from dual;------------為null時返回a,不會null返回原值

select nvl2(null,'a','b'),nvl2('1','a','b') from dual;--為null時返回b,不為null返回a

selectCOALESCE(null,5,6,null,9) from dual;-----返回第一個非空值

select POWER(2.2,2.2) from dual;  ----a的b次方

 

十、一些有用的字串操作函式:

select CHR(95) from dual;-------------ASCII碼對應字元

select ASCII('_') from dual;----------字元對應ASCII碼

select concat('aa','bb') from dual;------------等同於||

select INITCAP('whaT is this') from dual;------首字母大寫,其餘小寫

select TO_MULTI_BYTE('ABC abc 中華') from dual;----------半形變全形

select TO_SINGLE_BYTE('ABC abc中華') from dual;------全形變半形

select VSIZE('abc中華') from dual;-----返回位元組數

select INSTR('CORPORATE FLOOR','OR',3,2) from dual;----從第3位開始查詢第2個'OR'