sql-server - 在同一列中排序 Asc 和 desc
问题描述
我在表中有一个日期列,我想创建一个 SELECT 查询,该查询的结果顺序将是所有大于或等于今天日期的日期将是第一个,并且顺序应该是 ASC ,并且所有小于今天日期的日期将是第二个,并且顺序将为 DESC
顺序应如下所示:
笔记:
- 在以下列表中,日期格式为 YYYY-MM-DD
- 今天的日期是 2021 年 2 月 8 日
- 我的日期数据类型是
date
2021-02-08
2021-02-09
2021-05-18
2022-06-29<----This is the last bigger and equal then today
2021-02-07<----This is the first smaller then today
2021-02-06
2021-01-03
2020-12-06
2020-10-08
;with cte
as
(
select
CustomrId
,CustomrName
,SubscriptionDate
,SubscriptionInDays
,datediff(day, dateadd(DAY, SubscriptionInDays, SubscriptionDate), CAST(GETDATE() AS Date )) as DaysToEnd
from
TBL
)
select
CustomrId
,CustomrName
,SubscriptionDate
,SubscriptionInDays
,-iif(DaysToEnd > 0, 0 ,DaysToEnd) as DaysToEnd
from
cte
order by
case
when DaysToEnd = 0 then 0
when DaysToEnd > 0 then 1
end
,DaysToEnd
In this approach this is the result order I'm getting:
2021-02-08
2021-02-09
2021-05-18
2022-06-29<----This is the last bigger and equal then today
2020-10-08
2020-12-06
2021-01-03
2021-02-06
2021-02-07<----This is the first smaller then today
解决方案
您需要条件排序:
SELECT *
FROM tablename
ORDER BY
CASE WHEN datecolumn >= CONVERT(DATE, GETDATE()) THEN 1 ELSE 2 END,
ABS(DATEDIFF(day, CONVERT(DATE, GETDATE()), datecolumn))
请参阅演示。
结果:
日期栏 |
---|
2021-02-08 |
2021-02-09 |
2021-05-18 |
2022-06-29 |
2021-02-07 |
2021-02-06 |
2021-01-03 |
2020-12-06 |
2020-10-08 |
推荐阅读
- python - 如何处理从 For 循环返回的多个(相同)事件?
- javascript - 为什么 fetch 只在不在函数中时执行?
- azure - Terraform Azurerm azurerm_recovery_services_protected_vm “设置即时恢复快照的数量”
- google-maps - Google Places 自动填充小部件和内容安全策略
- python-3.x - dask.dataframe.read_parquet 耗时太长
- reactjs - ReactJS 中的 CURL 替代方案,从文件夹中的 URL 下载图像
- python - 准备训练数据集
- python - 具有客户端个人 ACK 的持久订户不起作用
- json - 尝试解码 JSON 日期时出现“JSON 写入 (__NSTaggedDate) 中的类型无效”
- xamarin.forms - 将宽度设置为与另一个控件相同