Myu*_*ran 24 t-sql sql-server sql-order-by isnull
我有一个日期列有一些NULL.我想按日期栏ASC订购,但我需要将NULLs放在底部.如何在TSQL上做到这一点?
Tho*_*ner 52
在标准SQL中,您可以指定放置空值的位置:
order by col asc nulls first
order by col asc nulls last
order by col desc nulls first
order by col desc nulls last
Run Code Online (Sandbox Code Playgroud)
但是T-SQL不符合这里的标准.NULL的顺序取决于您是在T-SQL中升序还是降序排序:
order by col asc -- implies nulls first
order by col desc -- implies nulls last
Run Code Online (Sandbox Code Playgroud)
使用整数,您可以简单地按负数排序:
order by -col asc -- sorts by +col desc, implies nulls first
order by -col desc -- sorts by +col asc, implies nulls last
Run Code Online (Sandbox Code Playgroud)
但是这对于日期(或者那个字符串)是不可能的,所以你必须首先排序为null /不是null,然后只有你的列:
order by case when col is null then 1 else 2 end, col asc|desc -- i.e. nulls first
order by case when col is null then 2 else 1 end, col asc|desc -- i.e. nulls last
Run Code Online (Sandbox Code Playgroud)
Select *
From YourTable
Order By case when DateCol is null then 0 else 1 end
,DateCol
Run Code Online (Sandbox Code Playgroud)
甚至 Order By IsNull(DateCol,'2525-12-31')