简体   繁体   中英

How can I convert hh:mm:ss to float in sql?

SELECT SUM(render) AS total FROM mytable

This is my code for getting the summation of all rendered hrs. But the output turned out to be like for instance I have 04:30:00 and 03:15:00, then the output turned to 074520, but I want it to be like 7.75 hrs

Here is one way to do it in MySQL:

SELECT 
    SUM(HOUR(render) * 60.0 + MINUTE(render)) / 60.0 AS TotalHours
FROM mytable

The expression HOUR(render) * 60.0 + MINUTE(render) converts time value into the number of minutes which we sum up to get the total.

You can add SECOND() to the formula to get a more precise answer if you want.

If you want to sum a time type in MySQL, use:

select sum(time_to_sec(render))
from mytable;

This converts the time to a seconds value, sums the value, Then, if you want to convert it back to another format, convert the seconds:

select sum(time_to_sec(render)) / (60 * 60) as decimal_hours,
       sec_to_time(sum(time_to_sec(render))) as time_format

MySQL does not directly sum time values. It is going to convert them to a number of the form HHMMSS. So, 00:00:55 is 55 . If you add it to itself you get 110 , which has nothing to do with 00:01:50 .

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