阿牛 发表于 2017-12-14 16:36:29

SQL Server排序的时候使null值排在最后

  首先建一个表插入一些测试数据
  create table UserInfo
  (

  UserInfoID      int not null>  User_No          int null,
  User_Names    nvarchar(16)   null
  )
  insert into UserInfo(User_No,User_Names)
  select '104','名称三' union all
  select '103','名称二' union all
  select'108','名称七' union all
  select '105','名称四'union all
  select'106','名称五' union all
  select '102','名称一' union all
  select '107','名称六' union all
  select'109' ,'名称八'
  insert into UserInfo(User_Names)
  select '名称九' union all
  select'名称十'
  select *from UserInfo
  下面先直接排序看下效果
  select UserInfoID,User_No,User_Names
  from UserInfo
  order by User_NO asc
  可以看到指定排序的列,其值为null的排在了最前面
  下面就是解决办法
  select UserInfoID,User_No,User_Names
  from UserInfo
  order by case when User_NO is null then 1 else 0 end asc,User_NO asc以上就是解决办法了,既把指定排序列的值为null的排在最后了,也可以按照指定的值进行排序,是不是很简单
页: [1]
查看完整版本: SQL Server排序的时候使null值排在最后