我需要进行一个基于日期列排序的查询,并遵循以下规则:
- 第一个:NULL
- 然后:如果日期 >= CURRENT_TIMESTAMP,则按 ASC 排序
- 最后:如果日期 < CURRENT_TIMESTAMP,则按 DESC 排序
我有以下内容:
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
但这不会按降序返回早于今天日期的项目。我如何修改我的查询以满足所有三个要求?
最佳答案
我们可以将它们分组,并在第一个 order by 子句中对组进行排序。
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
关于sql - 在同一列上按升序或降序有条件地排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27027805/