BlogProgramming

MySQL how to convert Time to Decimal or How to Average Time

Hi all,

today I’ve came across with a problem that I wanted to average time, get the average from a field type TIME (00:00:00) with only a query. I’ve started thinking of going and start breaking that string into bits (hours, minutes and seconds), convert all to seconds than make that average.

But there is a simpler way, MySQL has some TIME functions that can help you there, like TIME_TO_SEC and SEC_TO_TIME.
The process is simple, use TIME_TO_SEC to convert time to seconds, average it (AVG) and then convert it back to SEC_TO_TIME, all in a single line. Something like this example:

SELECT
	SEC_TO_TIME(
		AVG(
			TIME_TO_SEC(average_time)
		)
	)
FROM
	works

Any questions or comments? Please post it bellow.

Artigos Relacionados

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *

Este site utiliza o Akismet para reduzir spam. Fica a saber como são processados os dados dos comentários.

Botão Voltar ao Topo
João Clérigo - Photography
Fechar

AdBlocker Detetado
AdBlocker Detected

Por favor ajude este website permitindo a visualização de alguns anúncios. Obrigado. Please help this website allowing the view of some advertising. Thank you!