從emp表檢索員工的名字和職位,而且按照職位字段的最後兩個字符對檢索結果進行排序
MySQL & Oracle函數
select ename, job from emp order by substr(job, length(job)-2);
考慮以下視圖:spa
create view V as select ename || ' ' deptno as data from emp; select * from V;
以DEPTNO或者ENAME做爲排序項。使用REPLACE和TRANSLATE函數修改用於排序的字符串
Oracle 按DEPTNO排序code
select data from V order by replace(data, replace( translate(data,'0123456789','##########'),'#',''),'');
Oracle 按ENAME排序排序
select data from V order by replace( translate(data,'0123456789','##########'),'#','');
通用方式:使用case when語句標記NULL值與非NULL值ip
select ename, sal, comm from ( select ename, sal, comm, case when comm is null then 0 else 1 end as is_null from emp ) x order by is_null desc, comm;
針對Oracle 9i及後續版本,可使用ORDER BY子句的擴展語法NULLS FIRST和NULLS LAST來決定NULL值位置,無需考慮非NULL值的排序方式字符串
select ename, sal, comm from emp order by comm nulls first --nulls last;
例如,若是JOB等於SALESMAN,就按照COMM來排序;不然,按照SAL排序。it
select ename, sal, job, comm from emp order by case when job = 'SALESMAN' then comm else sal end;
《SQL經典實例》第二章