oracle中如何更改order by的默认排序?

oracle中如何更改order by的默认排序?

直接看问题:

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
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 进行并集,会报语法错误。解决方案是将结果集作为一个新的表,查询后再并集,即可。


方法二:

虚拟出来一个字段,规定排序规则,依据新的排序规则进行排序即可。

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


运行结果:






猜你喜欢

转载自blog.csdn.net/ma451152002/article/details/50913950