我有一个带有datetime字段的SQL表。所讨论的字段可以为空。我有一个查询,我想要的结果排序由datetime字段上升,但我想要的行,其中的datetime字段是空在列表的结束,而不是在开始。
有什么简单的方法可以做到吗?
我有一个带有datetime字段的SQL表。所讨论的字段可以为空。我有一个查询,我想要的结果排序由datetime字段上升,但我想要的行,其中的datetime字段是空在列表的结束,而不是在开始。
有什么简单的方法可以做到吗?
当前回答
select MyDate
from MyTable
order by case when MyDate is null then 1 else 0 end, MyDate
其他回答
如果您正在使用MariaDB,它们会在NULL值中提到以下内容 文档。
Ordering When you order by a field that may contain NULL values, any NULLs are considered to have the lowest value. So ordering in DESC order will see the NULLs appearing last. To force NULLs to be regarded as highest values, one can add another column which has a higher value when the main field is NULL. Example: SELECT col1 FROM tab ORDER BY ISNULL(col1), col1; Descending order, with NULLs first: SELECT col1 FROM tab ORDER BY IF(col1 IS NULL, 0, 1), col1 DESC; All NULL values are also regarded as equivalent for the purposes of the DISTINCT and GROUP BY clauses.
上面显示了两种按NULL值排序的方法,您可以将它们与 ASC和DESC关键字。例如,另一种获取NULL值的方法 首先是:
SELECT col1 FROM tab ORDER BY ISNULL(col1) DESC, col1;
-- ^^^^
当你的排序列是数字(像一个秩),你可以乘以-1,然后按顺序降序。它将保持您所期望的顺序,但将NULL放在最后。
select *
from table
order by -rank desc
使用NVL函数
select * from MyTable order by NVL(MyDate, to_date('1-1-1','DD-MM-YYYY'))
以下是最著名的DBMS中NVL的替代方案
SELECT *
FROM Employees
ORDER BY ISNULL(DepartmentId, 99999);
请看这篇博客文章。
在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