dmytroshved's avatar

Average on STRING cook_time column

I am struggling with MySQL query to get an average time on my cook_time column

The data in that column looks like:

cook_time

01:55
01:43
00:38

The format is H:M

How can I get an average time on that column even the column has STRING type?

0 likes
1 reply
Glukinho's avatar

Right answer would be to change column type from string "H:M" to integer seconds, getting averages and other calculations will be easy.

If you have to stick to current format, then you should extract hours/minutes strings from the field, convert to numbers and calculate minutes, something like this:

SELECT 
		SUBSTRING(cook_time, 1, 2) AS hours_str,
		SUBSTRING(cook_time, 4, 2) AS minutes_str,
		CAST(hours_str AS INTEGER) AS hours,
		CAST(minutes_str AS INTEGER) AS minutes,
		(hours * 60 + minutes) AS overall_minutes,
		AVG(overall_minutes) AS avg_minutes,
FROM
		cookings
WHERE
		...
1 like

Please or to participate in this conversation.