我有一个带有datetime字段的SQL表。所讨论的字段可以为空。我有一个查询,我想要的结果排序由datetime字段上升,但我想要的行,其中的datetime字段是空在列表的结束,而不是在开始。
有什么简单的方法可以做到吗?
我有一个带有datetime字段的SQL表。所讨论的字段可以为空。我有一个查询,我想要的结果排序由datetime字段上升,但我想要的行,其中的datetime字段是空在列表的结束,而不是在开始。
有什么简单的方法可以做到吗?
当前回答
order by coalesce(date-time-field,large date in future)
其他回答
order by -cast([nativeDateModify] as bigint) desc
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)
select MyDate
from MyTable
order by case when MyDate is null then 1 else 0 end, MyDate
(“有点”晚了,但这一点根本没有被提及)
您没有指定您的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