在SQL中减去两个日期并获得结果的天数

时间:2013-01-02 09:03:12

标签: sql sql-server tsql

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

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

7 个答案:

答案 0 :(得分:70)

使用DATEDIFF

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

答案 1 :(得分:7)

使用DATE_DIFF

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

答案 2 :(得分:6)

编辑: 似乎我对代码示例的性能有误。 表现最佳的是在发布的案例中以秒为单位的片段。 这证明了我试图解释的内容,时间差异并不那么引人注目:

----------------------------------
--  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())

请原谅我迟到和我粗略评论的例子,但我认为提及SARG很重要。

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

虽然下面代码中的临时表没有索引,但是表达式和​​表中的值之间进行比较,而不是修改表中的值的表达式和不变。 希望这被认为是有用的。

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())

答案 3 :(得分:1)

怎么样

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

答案 4 :(得分:1)

SELECT DATEDIFF(day,'2014-06-05','2014-08-05') AS DiffDate

diffdate是列名。

结果:

DiffDate

23

答案 5 :(得分:0)

SELECT (to_date('02-JAN-2013') - to_date('02-JAN-2012')) days_between
FROM dual
/

答案 6 :(得分:0)

语法

DATEDIFF(expr1,expr2)

说明

DATEDIFF() 返回 (expr1 – expr2) 表示为从一个日期到另一个日期的天数。 expr1 和 expr2 是日期或日期和时间表达式。计算中仅使用值的日期部分。

@D Stanley