TSQL SELECT DISTINCT最后由ASC NULLS订购

Mig*_*Mas 1 sql t-sql select distinct sql-order-by

有:

SELECT DISTINCT TOP 100 * FROM mytable ORDER BY date ASC
Run Code Online (Sandbox Code Playgroud)

如何使日期中的空值最后?

非常感谢.

Gor*_*off 5

有些数据库支持最后一个NULL的语法order by,有些则不支持.所以,我使用:

select distinct top 100 *
from MyTable
order by  (case when date is null then 1 else 0 end), date asc
Run Code Online (Sandbox Code Playgroud)

或者,如果我不想打字那么多:

order by coalesce(date, '9999-12-12')  -- or something like that
Run Code Online (Sandbox Code Playgroud)

您还可以将distinct放在子查询中:

select top 100 *
from (select distinct *
      from mytable
     ) t
order by (case when date is null then 1 else 0 end), date asc
Run Code Online (Sandbox Code Playgroud)

date但是,假设它在列列表中,第一个版本应该可以工作.