在SQL中减去两个date并得到结果的日子

Select I.Fee From Item I WHERE GETDATE() - I.DateCreated < 365 days 

我怎样才能减去两天? 结果应该是几天。 例如:365天。 500天..等等…

使用DATEDIFF

 Select I.Fee From Item I WHERE DATEDIFF(day, GETDATE(), I.DateCreated) < 365 

使用DATE_DIFF

 Select I.Fee From Item I WHERE DATEDIFF(day, GETDATE(), I.DateCreated) < 365 
  • DATE_DIFF

编辑:这似乎是错误的代码示例的性能。 最好的执行者是所张贴的案例中的第二个片段。 这表明了我想要解释的事情,时间差异并不那么显着:

 ---------------------------------- -- Monitor time differences ---------------------------------- CREATE CLUSTERED INDEX dtIDX ON #ArbDates (MyDate) DECLARE @Stopwatch DATETIME SET @Stopwatch = GETDATE() -- SARGABLE SELECT * FROM #ArbDates WHERE MyDate > DATEADD(DAY, -364, '2010-01-01') PRINT DATEDIFF(MS, @Stopwatch, GETDATE()) SET @Stopwatch = GETDATE() -- NOT SARGABLE SELECT * FROM #ArbDates WHERE DATEDIFF(DAY, MyDate, '2010-01-01') < 365 PRINT DATEDIFF(MS, @Stopwatch, GETDATE()) 

不好意思,我迟到了,还有我粗暴评论的例子,但是我认为提到特区政府是很重要的。

 SELECT I.Fee FROM Item I WHERE I.DateCreated > DATEADD(DAY, -364, GETDATE()) 

尽pipe下面的代码中的临时表没有索引,但性能仍然得到增强,因为表中的expression式和值之间进行了比较,而不是修改表中的值和常量的expression式。 希望这被发现是有用的。

 USE tempdb GO IF OBJECT_ID('tempdb.dbo.#ArbDates') IS NOT NULL DROP TABLE #ArbDates DECLARE @Stopwatch DATETIME ---------------------------------- -- Build test data: 100000 rows ---------------------------------- ;WITH Base10 (n) AS ( SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 ) ,Base100000 (n) AS ( SELECT 1 FROM Base10 T1, Base10 T3, Base10 T4, Base10 T5, Base10 T6 ) SELECT MyDate = CAST(RAND(CHECKSUM(NEWID()))*3653.0+36524.0 AS DATETIME) INTO #ArbDates FROM Base100000 ---------------------------------- -- Monitor time differences ---------------------------------- SET @Stopwatch = GETDATE() -- NOT SARGABLE SELECT * FROM #ArbDates WHERE DATEDIFF(DAY, MyDate, '2010-01-01') < 365 PRINT DATEDIFF(MS, @Stopwatch, GETDATE()) SET @Stopwatch = GETDATE() -- SARGABLE SELECT * FROM #ArbDates WHERE MyDate > DATEADD(DAY, -364, '2010-01-01') PRINT DATEDIFF(MS, @Stopwatch, GETDATE()) 

怎么样

 Select I.Fee From Item I WHERE (days(GETDATE()) - days(I.DateCreated) < 365) 
 SELECT (to_date('02-JAN-2013') - to_date('02-JAN-2012')) days_between FROM dual / 
 SELECT DATEDIFF(day,'2014-06-05','2014-08-05') AS DiffDate 

diffdate是列名称。

结果:

DiffDate

23