SQL日期差异忽略了几年

时间:2017-10-29 15:56:24

标签: sql sql-server tsql

我有两个日期列,我想计算他们在月/日的差异并排除年份。

假设第一个日期是2017年10月30日,将其与当前日期进行比较,其差异应为1。如果当前日期是10/30/2018,则差异也应为1。

一些例子:

Schedule Date:10/30/2017   Current Date 10/29/2017  Diff  1
Schedule Date:10/30/2017   Current Date 11/30/2017  Diff 30
Schedule Date:10/30/2017   Current Date 10/29/2018  Diff 1
Schedule Date:10/30/2017   Current Date 11/30/2018  Diff 30
Schedule Date:10/30/2017   Current Date 10/29/2019  Diff 1
Schedule Date:10/30/2017   Current Date 11/30/2019  Diff 30

3 个答案:

答案 0 :(得分:0)

试试这个

 SELECT ABS(365 * DATEDIFF(year, '10/30/2017', '11/30/2018')
 -  DATEDIFF(day, '10/30/2017', '11/30/2018')) AS DateDiff; 

请注意,10/30/11/30/之间的差异不能超过30天。这是31天。

答案 1 :(得分:0)

您可以使用Common Table Expression来获得如下结果:

DECLARE @Schedule_Date datetime = '10/30/2017'
DECLARE @Current_Date datetime = '11/30/2019'

;WITH usingCTE AS 
(
    SELECT CAST(STUFF(CONVERT(varchar, @Schedule_Date, 102), 1, 4, CAST(YEAR(@Current_Date) AS varchar)) AS datetime) AS Schedule_Date 
)
SELECT abs(DATEDIFF(day, @Current_Date, Schedule_Date)) FROM usingCTE

查询的另一种方法:

DECLARE @Schedule_Date datetime = '10/30/2017'
DECLARE @Current_Date datetime = '11/30/2017'

SELECT ABS(DATEDIFF(day, 
           REPLACE(@Schedule_Date, DATEPART(year, @Schedule_Date), 
           DATEPART(year, @Current_Date)), -- replace the year with current year
           @Current_Date)) 

答案 2 :(得分:0)

这可能对你有用,首先将日期调整到同一年,然后计算两个日期之间不同的天数:

DECLARE @ScheduleDate DATE = '2017-10-30';
DECLARE @Dates TABLE (CurrentDate DATE);
INSERT INTO @Dates VALUES ('2017-10-29'),('2017-11-30'),('2018-10-29'),('2018-11-30'),('2019-10-29'),('2019-11-30');
SELECT @ScheduleDate ScheduleDate, *
FROM @Dates a
CROSS APPLY (SELECT AdjustedDate=DATEADD(YEAR, YEAR(@ScheduleDate) - YEAR(a.CurrentDate), a.CurrentDate)) b
CROSS APPLY (SELECT Diff=ABS(DATEDIFF(DAY, @ScheduleDate, b.AdjustedDate))) c