1. 程式人生 > >ORACLE自定義順序排序

ORACLE自定義順序排序

ORACLE可以藉助DECODE函式,自定義順序排序:

複製程式碼

select * from (
    select 'Nick' as item from dual
    union all
    select 'Viki' as item from dual
    union all
    select 'Glen' as item from dual
    union all
    select 'Robin' as item from dual
    union all
    select 'Total' as item from dual
) pre_tab
order by decode(item, 'Viki', 1, 'Glen', 2, 'Robin', 3, 'Nick', 4, 'Total', 99);

複製程式碼

 

另外,在Report開發中,常需要將Total放最後,其它項則按其它排序方式(一般按正常的升序),可看作同一列有兩種排序方式,那麼可以這樣:

複製程式碼

select * from (
    select 'Nick' as item from dual
    union all
    select 'Viki' as item from dual
    union all
    select 'Glen' as item from dual
    union all
    select 'Robin' as item from dual
    union all
    select 'Total' as item from dual
) pre_tab
order by decode(item, 'Total', 2, 1), item;

複製程式碼

 

作者:Nick Huang 部落格:http://www.cnblogs.com/nick-huang/ 本部落格為學習、筆記之用,以筆記形式記錄學習的知識與感悟。學習過程中可能參考各種資料,如覺文中表述過分引用,請務必告知,以便迅速處理。如有錯漏,不吝賜教。