简体   繁体   中英

Mysql difference in two dates with days and minutes result

I would like to ask if there is any possibility to run a query like bellow

Table
--
ID, Date1, Date2 (Dates are defined as datetime)

Show I want the Average datetime between Date1 and Sate2

eg

Table
--
1, 2013-12-12 16:00:00, 2013-12-13 16:00:00
2, 2013-12-13 15:00:00, 2013-12-14 17:00:00

Result 1 day and 1 hour and 0 minutes and 0 seconds

I've done so far like this

SELECT SEC_TO_TIME(AVG(UNIX_TIMESTAMP(SUBTIME(Date2, TIME(Date1))) - UNIX_TIMESTAMP(DATE(Date2)))) as AVGTime 
FROM Table

and the result is not as expected... it shows 30 minutes and some minutes and i think is somehting like 1 day and some hours....

It is better for you to understand the problem, i can explain like.... Consider that there is a company with some stuff. The stuff gets questions in Date1 and answers in Date2... I want to know what is the average time that the whole stuff answers the questions...

Try this query -

SELECT
  AVG(DATEDIFF(date2, date1)) days,
  SEC_TO_TIME(AVG(TIME_TO_SEC(TIMEDIFF(date2, date1)))) time
FROM
  table

in your case it gives, 25:00:00 (similar to 1 day, 1 hour and 0 minutes)

select SEC_TO_TIME(AVG(TIMESTAMPDIFF(SECOND,date1,date2))) from table

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