首页 > 解决方案 > 在同一列中排序 Asc 和 desc

问题描述

我在表中有一个日期列,我想创建一个 SELECT 查询,该查询的结果顺序将是所有大于或等于今天日期的日期将是第一个,并且顺序应该是 ASC ,并且所有小于今天日期的日期将是第二个,并且顺序将为 DESC

顺序应如下所示:

笔记:

  1. 在以下列表中,日期格式为 YYYY-MM-DD
  2. 今天的日期是 2021 年 2 月 8 日
  3. 我的日期数据类型是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

标签: sql-servertsqlsql-order-by

解决方案


您需要条件排序:

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

推荐阅读