小编典典

如何找到两个日期之间的天数

sql

我有一个基本的查询:

SELECT dtCreated
    , bActive
    , dtLastPaymentAttempt
    , dtLastUpdated
    , dtLastVisit
FROM Customers
WHERE (bActive = 'true') 
    AND (dtLastUpdated > CONVERT(DATETIME, '2012-01-0100:00:00', 102))

我想在输出中添加另一列…让我们称其为“差异”以找出“ dtcreated”和“
dtlastupdated”之间的天数,例如,如果记录1的dtcreated为1/1/11和dtlastupdated为1/1/12,则“差异”列将为“
365”。

可以在查询中完成吗?


阅读 171

收藏
2021-03-23

共1个答案

小编典典

您将使用DATEDIFF

declare @start datetime
declare @end datetime

set @start = '2011-01-01'
set @end = '2012-01-01'

select DATEDIFF(d, @start, @end)

results = 365

所以对于您的查询:

SELECT dtCreated
    , bActive
    , dtLastPaymentAttempt
    , dtLastUpdated
    , dtLastVisit
    , DATEDIFF(d, dtCreated, dtLastUpdated) as Difference
FROM Customers
WHERE (bActive = 'true') 
    AND (dtLastUpdated > CONVERT(DATETIME, '2012-01-0100:00:00', 102))
2021-03-23