直接看問題:
[sql] view plain copy 在CODE上檢視程式碼片派生到我的程式碼片
select * from scott.emp p order by p.job;
執行結果為:
透過order by 出來的排序結果以此為:ANALYST、CLERK、MANAGER、PRESIDENT、SALESMAN...
需求:
現要求排序結果為MANAGER為第一個顯示、CLERK為第二個顯示,其他預設排序
方法一:
透過union all 分別查詢後合併實現。
select *
from (select * from scott.emp where job in "MANAGER" order by job)
union all
from (select * from scott.emp where job = "CLERK" order by job)
from (select * from scott.emp where job not in ("MANAGER", "CLERK") order by job)
備註:
1、這裡應該採用union all 進行並集,不應該使用union。因為union,會對結果集進行排序,而union all 不排序。
2、這裡的子查詢中如果有order by 語句,不能直接使用union all 進行並集,會報語法錯誤。解決方案是將結果集作為一個新的表,查詢後再並集,即可。
方法二:
虛擬出來一個欄位,規定排序規則,依據新的排序規則進行排序即可。
select
p.*,
case to_char(p.job)
when "CLERK" then "2"
when "MANAGER" then "1"
else "999"
end neworder
from scott.emp p
order by neworder,p.job
直接看問題:
[sql] view plain copy 在CODE上檢視程式碼片派生到我的程式碼片
select * from scott.emp p order by p.job;
執行結果為:
透過order by 出來的排序結果以此為:ANALYST、CLERK、MANAGER、PRESIDENT、SALESMAN...
需求:
現要求排序結果為MANAGER為第一個顯示、CLERK為第二個顯示,其他預設排序
方法一:
透過union all 分別查詢後合併實現。
[sql] view plain copy 在CODE上檢視程式碼片派生到我的程式碼片
select *
from (select * from scott.emp where job in "MANAGER" order by job)
union all
select *
from (select * from scott.emp where job = "CLERK" order by job)
union all
select *
from (select * from scott.emp where job not in ("MANAGER", "CLERK") order by job)
執行結果為:
備註:
1、這裡應該採用union all 進行並集,不應該使用union。因為union,會對結果集進行排序,而union all 不排序。
2、這裡的子查詢中如果有order by 語句,不能直接使用union all 進行並集,會報語法錯誤。解決方案是將結果集作為一個新的表,查詢後再並集,即可。
方法二:
虛擬出來一個欄位,規定排序規則,依據新的排序規則進行排序即可。
[sql] view plain copy 在CODE上檢視程式碼片派生到我的程式碼片
select
p.*,
case to_char(p.job)
when "CLERK" then "2"
when "MANAGER" then "1"
else "999"
end neworder
from scott.emp p
order by neworder,p.job