简体   繁体   中英

Calculate difference of two dates in SQL

I have a table that contains 2 date/time columns (CreatedDateTime / LastModifiedDateTime):

Item   CreatedDateTime            LastModifiedDateTime

1      2016-03-18 18:49:36.557    2016-03-22 18:51:10.950

2      2016-03-22 17:32:57.610    2016-03-22 17:37:26.790

I would like to:

  1. Calculate the difference between CreatedDateTime and today's date (to give me an 'age')
  2. Calculate the difference between LastModifiedDateTime and today's date (to give me an idea of iactivity)

With 2. above, I want to be able to report on an Item that has not been 'modified' (LastModifiedDateTime) in a while.

Can anyone point me in the right direction?

If you are using SQL SERVER:

SAMPLE DATA:

CREATE TABLE #Temp(Item                 INT
              , CreatedDateTime      DATETIME
              , LastModifiedDateTime DATETIME);

INSERT INTO #Temp
VALUES
      (1
     , '2016-03-18 18:49:36.557'
     , '2016-03-22 18:51:10.950'),
      (2
     , '2016-03-22 17:32:57.610'
     , '2016-03-22 17:37:26.790');

QUERY:

SELECT A.Item
    , A.CreatedDateTime
    , A.LastModifiedDateTime
    , Age = DATEDIFF(day,A.CreatedDateTime,GETDATE())
    , inactivity = DATEDIFF(day,A.LastModifiedDateTime,GETDATE())
FROM   #Temp AS A;

RESULT:

在此处输入图片说明

You can use the DATEDIFF() function for the age and GETDATE() function for the current date.

You will just need to enter DATEDIFF(day,CreatedDateTime,GETDATE()), or a similar query.

Datediff() will also allow you to take month, hour, or other time measures.

Also with #2, you could throw in some CASE WHEN LastModifiedDateTime IS NULL THEN ... to give yourself a different report on that.

The DATEDIFF() function returns the time between two dates.

Syntax DATEDIFF(datepart,startdate,enddate);

SELECT DATEDIFF(day,'2014-06-05','2014-08-05') AS DiffDate

Result

DiffDate

61

Swapping the dates would result in a negative result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM