SQLCookbook 學習筆記 結果排序,印象筆記排序

來源:互聯網
上載者:User

SQLCookbook 學習筆記 結果排序,印象筆記排序


select name from emp order by salary;
ORDER BY 預設是按照升序排列, 當需要倒序時 用 ORDRE BY salary DESC


ORDER BY  不一定要基於列名 ,也可以用數字表示 基於第幾列:
select name from emp order by 3;         salary是從左至右第三列。


按照多個欄位排序


select * from emp order by depno, salary desc;
按照部門升序,在部門內部按照工資降序排列。


按字串排序
select *from  emp order by substr(job,length(job) - 2)
按照工作欄位的 最後兩個字元排序。


對字母數字混合的排序
MySQL不支援TRANSLATE函數,無解決方案。


處理排序空值
使用CASE 將空值 轉化為 0 或者1,這樣可以控制空值在排序中的位置。


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, comm desc
上述方法使用了一個附加列


ORACLE中有 NULLS FIRST 和 NULLS LAST 來確保NULL的排序方式。


內斂視圖 是一個中間結果,不輸出。


根據資料項目的鍵排序。
如果job是salasman 就根據COMM 來排序,否則根據sal來排序。
在ORDER BY 子句中 使用CASE運算式
select ename,sal,job,comm 
from emp
order by case when job = 'SALESMAN' then comm else sal end
類似是有 一個輔助列。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.