码迷,mamicode.com
首页 > 数据库 > 详细

sql查询结果集根据指定条件排序的方法

时间:2015-05-13 19:31:56      阅读:474      评论:0      收藏:0      [点我收藏+]

标签:

oracle认为 null 最大。

升序排列,默认情况下,null值排后面。

降序排序,默认情况下,null值排前面。

有几种办法改变这种情况:

(1)用 nvl 函数或decode 函数 将null转换为一特定值

(2)用case语法将null转换为一特定值(oracle9i以后版本支持。和sqlserver类似):
 1.当值为某个值的时候,指定排序的时候的位置
  select * from (
  select 1 t from dual
  union all
  select 2 t  from dual
  union all
  select 3 t from dual
  union all
  select 4 t from dual
  ) a  order by case when a.t=2 then 1 else 0 end
 2.当值为某个值的时候,排序的时候,永远在最后
  select * from (
  select 1 t from dual
  union all
  select 2 t  from dual
  union all
  select 3 t from dual
  union all
  select 4 t from dual
  ) a  order by case when a.t=2 then null else 0 end asc  nulls last

结果:

技术分享

技术分享

(3)使用nulls first 或者nulls last 语法。

这是oracle专门用来null值排序的语法。

nulls first :将null排在最前面。如:select * from mytb order by mycol nulls first

null last :将null排在最后面。如:select * from mytb order by mycol nulls last

如果要想让含有null的列按照自己的意愿进行排序,可做如上处理。

sql查询结果集根据指定条件排序的方法

标签:

原文地址:http://www.cnblogs.com/qadada/p/4501150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!