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

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


当前回答

order by coalesce(date-time-field,large date in future)

其他回答

解决方案使用“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)  

使用NVL函数

  select * from MyTable order by NVL(MyDate, to_date('1-1-1','DD-MM-YYYY'))

以下是最著名的DBMS中NVL的替代方案

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

在Oracle中,你可以使用NULLS FIRST或NULLS LAST:指定NULL值应该在非NULL值之前或之后返回:

ORDER BY { column-Name | [ ASC | DESC ] | [ NULLS FIRST | NULLS LAST ] }

例如:

ORDER BY date DESC NULLS LAST

裁判:http://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj13658.html

(“有点”晚了,但这一点根本没有被提及)

您没有指定您的DBMS。

在标准SQL(以及大多数现代DBMS,如Oracle, PostgreSQL, DB2, Firebird, Apache Derby, HSQLDB和H2)中,您可以指定NULLS LAST或NULLS FIRST:

使用NULLS LAST将它们排序到最后:

select *
from some_table
order by some_column DESC NULLS LAST