Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql SEC_TO_TIME without trailing seconds - Solution Found

Tags:

mysql

I have a Mysql table that stores dates in the format (YYYY-MM-DD HH:MM:SS).

What i want is to SUM the HH:MM:SS part for the selected rows, so as i found in another post i use the query

SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(date))) FROM table

This query works. It sums the part that i want and returns it in the format HH:MM:SS.

My question is if its possible to strip of the seconds from the result.

I have to do this in the query, as the CMS that i use doesn't allow me to use php on this part.

By the way it would be amazing if i could return the result in days, hours and minutes in case the sum is greater that 24 hours.

Thanks in advance

For anyone interested i found the solution

SELECT TIME_FORMAT(SEC_TO_TIME(SUM(TIME_TO_SEC(hours))),'%H:%i' ) FROM table
like image 986
tliokos Avatar asked Mar 27 '12 09:03

tliokos


1 Answers

Try this query, it will calculate days, hours and minutes -

SELECT
  SUM(TIME_TO_SEC(date) DIV 86400) days,
  SUM(EXTRACT(HOUR FROM (SEC_TO_TIME(TIME_TO_SEC(date) % 86400)))) hours,
  SUM(EXTRACT(MINUTE FROM (SEC_TO_TIME(TIME_TO_SEC(date) % 86400)))) minutes
FROM table

Then use CONCAT function to format these result into one string.

like image 134
Devart Avatar answered Nov 08 '22 01:11

Devart