Search code examples
mysqlsql-timestamp

Sum multiple times produced in a query (timediff)


I have two fields:

  • Initial (timestamp)
  • Final (timestamp)

My query is:

SELECT TIMEDIFF(Final, Initial) 
    AS 'Worked Hours' 
    FROM `db_foo`
    WHERE matriculation='X' AND date='2017-yy-yy'

The result will be something like

Worked Hours    
03:34:00
02:34:00
01:00:00
[...]

Would it be possible to further sum those multiple timestamps, so to have the TOTAL amount of worked hours?

Example dataset (exported in csv):

DATE --- ID --- INITIAL --- FINAL --- MATRICULATION

2017-09-14,"29","2017-09-14 11:00:00","2017-09-14 14:34:00","4"
2017-09-14,"30","2017-09-14 17:00:00","2017-09-14 19:34:00","4"
2017-09-14,"31","2017-09-14 21:00:00","2017-09-14 22:00:00","4"

Desired output (it is the sum of the working times):

Worked Hours
07:08:00

Thanks in advance


Solution

  • To get the desired result you can use following query

    SELECT SEC_TO_TIME(
      SUM(
        TIMESTAMPDIFF(SECOND,Initial,Final)
      )
    )
    FROM `db_foo` /* WHERE clause*/; 
    

    To get the total sum along with previous result set you can follow below approach

    SELECT t.*,SEC_TO_TIME(SUM(workedhours))
    FROM (
      SELECT ID, TIMESTAMPDIFF(SECOND,Initial,Final)  workedhours
      FROM `db_foo`  /* WHERE clause*/
     ) t
    GROUP BY ID WITH ROLLUP;
    

    DEMO