天天看點

選讀SQL經典執行個體筆記01_檢索和排序

作者:躺着的柒
選讀SQL經典執行個體筆記01_檢索和排序

1. 在WHERE子句中引用别名列

1.1. 當表裡的某些列沒有被恰當命名的時候,這個技巧尤其有用

1.2. sql

select sal as salary, comm as commission
  from emp
 where salary < 5000           

1.3. 内嵌視圖

1.3.1. sql

select *
   from (
 select sal as salary, comm as commission
   from emp
        ) x
  where salary < 5000           

1.3.2. 聚合函數

1.3.3. 标量子查詢

1.3.4. 視窗函數

1.3.5. 别名

2. CONCAT函數

2.1. 串聯多列的值

2.2. 在DB2、Oracle和PostgreSQL 中,“||”是CONCAT函數的快捷方式

2.3. 在SQL Server中則為“+”

3. 随機傳回若幹行記錄

3.1. 如果ORDER BY子句使用數值常量,那麼就需要按照SELECT清單裡的順序來排序

3.2. 如果ORDER BY子句使用了函數,那麼就需要按照該函數的傳回值來排序,而函數傳回的值是根據結果集裡的每一行計算而來的

3.3. MySQL

3.3.1. sql

select ename,job
 from emp
  order by rand() limit 5           

3.4. PostgreSQL

3.4.1. sql

select ename,job
   from emp
  order by random() limit 5           

3.5. Oracle

3.5.1. sql

select *
   from (
  select ename, job
    from emp
   order by dbms_random.value()
        )
   where rownum <= 5           

3.6. SQL Server

3.6.1. sql

select top 5 ename,job
   from emp
  order by newid()           

4. 把Null值轉換為實際值

4.1. COALESCE函數

4.1.1. sql

select coalesce(comm,0)
   from emp           

4.1.2. 更友善、更簡潔

4.2. CASE

4.2.1. sql

select case
       when comm is not null then comm
       else 0
       end
  from emp           

4.3. 适用于所有的資料庫

5. 依據子串排序

5.1. 按照職位字段的最後兩個字元對檢索結果進行排序

5.2. DB2、MySQL、Oracle和PostgreSQL

5.2.1. sql

select ename,job
  from emp
 order by substr(job,length(job)-2)           

5.3. SQL Server

5.3.1. sql

select ename,job
  from emp
 order by substring(job,len(job)-2,2)           

6. 排序時對Null值的處理

6.1. Oracle能夠讓你在無須修改非Null值資料的情況下友善地把Null值排到最前面或者最後面,其他資料庫得添加一個輔助列

6.1.1. Oracle 9i及後續版本NULLS FIRST和NULLS LAST來決定Null值應該排到前面還是後面

6.2. 輔助列

6.2.1. 隻存在于查詢語句裡,而不存在于表中

6.2.2. 目的是讓你能夠識别出Null值,并控制其排在最前面還是最後面

6.3. 對于非Oracle解決方案的查詢語句,其内嵌視圖X會傳回如下結果集

6.4. sql

select ename,sal,comm,
       case when comm is null then 0 else 1 end as is_null
  from emp           

7. 依據條件邏輯動态調整排序項

7.1. 如果JOB等于SALESMAN,就要按照COMM來排序;否則,按照SAL排序

7.2. sql

select ename,sal,job,comm
   from emp
  order by case when job = 'SALESMAN' then comm else sal end           

7.3. sql

select ename,sal,job,comm,
       case when job = 'SALESMAN' then comm else sal end as ordered
 from emp
order by 5