【发布时间】:2016-11-15 17:08:12
【问题描述】:
给定以下数据:
Effective Date
--------------
2014-01-01
2015-01-01
2016-01-01
2017-01-01
2018-01-01
我想按相对于(例如)2016-06-01 的日期排序,其中所有低于2016-06-01 的降序值都位于高于2016-06-01 的所有升序值之前。
Relative to date: 2016-06-01 the desired ordering is
Effective Date
--------------
2016-01-01
2015-01-01
2014-01-01
2017-01-01
2018-01-01
我想出的实现所需排序的最佳方法是:
CREATE TABLE #Dates
(
EffectiveDate DATETIME2
);
DECLARE @CurrentDate DATETIME2 = '2016-06-01';
DECLARE @MinDate DATETIME2 = '0001-01-01';
INSERT INTO #Dates (EffectiveDate) VALUES ('2014-01-01');
INSERT INTO #Dates (EffectiveDate) VALUES ('2015-01-01');
INSERT INTO #Dates (EffectiveDate) VALUES ('2016-01-01');
INSERT INTO #Dates (EffectiveDate) VALUES ('2017-01-01');
INSERT INTO #Dates (EffectiveDate) VALUES ('2018-01-01');
SELECT
*
FROM
#Dates
ORDER BY
CASE
WHEN #Dates.EffectiveDate < @CurrentDate
THEN DATEDIFF(DAY, #Dates.EffectiveDate, @CurrentDate)
ELSE
DATEDIFF(DAY, @CurrentDate, #Dates.EffectiveDate) - DATEDIFF(DAY, @CurrentDate, @MinDate)
END;
DROP TABLE #Dates;
有没有更好的方法来实现所需的排序?
【问题讨论】:
标签: sql sql-server tsql date