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

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

4

7 回答 7

73

使用DATEDIFF

Select I.Fee
From Item I
WHERE  DATEDIFF(day, GETDATE(), I.DateCreated) < 365
于 2013-01-02T09:04:19.947 回答
8

利用DATE_DIFF

Select I.Fee
From   Item I
WHERE  DATEDIFF(day, GETDATE(), I.DateCreated)  < 365
于 2013-01-02T09:04:33.933 回答
7

编辑:似乎我对代码示例的性能有误。表现最好的是在发布的案例中第二个运行的片段。这证明了我试图解释的内容,并且时间差异并不那么明显:

----------------------------------
--  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())
于 2013-01-02T09:51:05.053 回答
3
SELECT DATEDIFF(day,'2014-06-05','2014-08-05') AS DiffDate

diffdate 是列名。

结果:

差异日期

23

于 2015-05-25T12:43:55.717 回答
2

怎么样

Select I.Fee
From Item I
WHERE  (days(GETDATE()) - days(I.DateCreated) < 365)
于 2013-07-11T04:18:10.220 回答
1
SELECT (to_date('02-JAN-2013') - to_date('02-JAN-2012')) days_between
FROM dual
/
于 2013-01-02T13:45:58.300 回答
0

句法

DATEDIFF(expr1,expr2)

描述

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

@D 斯坦利

于 2021-02-01T05:39:41.777 回答