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

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


当前回答

SELECT *          
FROM Employees
ORDER BY ISNULL(DepartmentId, 99999);

请看这篇博客文章。

其他回答

SELECT *          
FROM Employees
ORDER BY ISNULL(DepartmentId, 99999);

请看这篇博客文章。

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

使用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

我也偶然发现了这一点,以下似乎为我做的伎俩,在MySQL和PostgreSQL:

ORDER BY date IS NULL, date DESC

详见https://stackoverflow.com/a/7055259/496209