How to find the number of days between two dates

2020-07-03 04:10发布

I have a basic query:

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

I want to add another column to the output... lets call it "Difference" to find out the number of days between 'dtcreated' and 'dtlastupdated' So for example if record 1 has a dtcreated of 1/1/11 and dtlastupdated is 1/1/12 the "Difference" column would be "365".

Can this be accomplished in a query?

9条回答
劳资没心,怎么记你
2楼-- · 2020-07-03 04:27

Get No of Days between two days

DECLARE @date1 DATE='2015-01-01',
 @date2 DATE='2019-01-01',
 @Total int=null

SET @Total=(SELECT DATEDIFF(DAY, @date1, @date2))
PRINT @Total
查看更多
聊天终结者
3楼-- · 2020-07-03 04:35

I would use the DATE_DIFF function to provide this value as below:

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

EDIT: IF using MySQL you omit the 'd' leaving you with

DATEDIFF(dtLastUpdated, dtCreated) AS Difference
查看更多
4楼-- · 2020-07-03 04:38

You would use DATEDIFF:

declare @start datetime
declare @end datetime

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

select DATEDIFF(d, @start, @end)

results = 365

so for your query:

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))
查看更多
登录 后发表回答