Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the number of days between two dates

Tags:

sql

sql-server

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?

like image 829
Shmewnix Avatar asked Jul 10 '12 17:07

Shmewnix


People also ask

How do you calculate the number of days from two dates?

To calculate the number of days between two dates, you need to subtract the start date from the end date. If this crosses several years, you should calculate the number of full years. For the period left over, work out the number of months. For the leftover period, work out the number of days.

How do I calculate days between two dates in Excel?

To find the number of days between these two dates, you can enter “=B2-B1” (without the quotes into cell B3). Once you hit enter, Excel will automatically calculate the number of days between the two dates entered.


1 Answers

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))
like image 88
Taryn Avatar answered Oct 12 '22 11:10

Taryn