我需要根据具有以下规则的日期列进行排序查询:
我有以下内容:
SELECT * FROM [Table]
ORDER BY (CASE WHEN [Date] IS NULL THEN 0 ELSE 1 END),
(CASE WHEN [Date] >= CAST(CURRENT_TIMESTAMP AS DATE) THEN 0 ELSE 1 END),
[Date] ASC
但是这不会按降序返回比今天更早的项目。如何修改我的查询以满足所有三个要求?
答案 0 :(得分:1)
我们可以将它们分组并按照第一顺序子句对组进行排序。
SELECT *
from test
order by (case when [Date] is null then 0
when [Date] >= getdate() then 1
when [Date] < getdate() then 2
end ) asc ,
case when [Date] >= getdate() then [Date] end asc,
case when [Date] < getdate() then [Date] end desc