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?
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With