我有一个带有datetime字段的SQL表。所讨论的字段可以为空。我有一个查询,我想要的结果排序由datetime字段上升,但我想要的行,其中的datetime字段是空在列表的结束,而不是在开始。

有什么简单的方法可以做到吗?


当前回答

select MyDate
from MyTable
order by case when MyDate is null then 1 else 0 end, MyDate

其他回答

order by coalesce(date-time-field,large date in future)
order by -cast([nativeDateModify] as bigint) desc
select MyDate
from MyTable
order by case when MyDate is null then 1 else 0 end, MyDate

解决方案使用“case”是通用的,但不使用索引。

order by case when MyDate is null then 1 else 0 end, MyDate

就我而言,我需要表现。

 SELECT smoneCol1,someCol2  
 FROM someSch.someTab
 WHERE someCol2 = 2101 and ( someCol1 IS NULL ) 
  UNION   
 SELECT smoneCol1,someCol2
 FROM someSch.someTab
 WHERE someCol2 = 2101 and (  someCol1 IS NOT NULL)  

当你的排序列是数字(像一个秩),你可以乘以-1,然后按顺序降序。它将保持您所期望的顺序,但将NULL放在最后。

select *
from table
order by -rank desc