I have a table in MySQL that stores events by time with the following structure:
id / num_veh / time
I would like to create a SQL query that returns the events in groups by time range. For example:
From 01:00 to 06:00 - 500 items / From 07:00 to 12:00 - 800 items
I researched a lot about it and I believe I'm pretty close with the following SQL:
SELECT grupos, SUM(num_veh) as quantidade
FROM (
SELECT( CASE
WHEN DATE_FORMAT(time, '%H:%i:%s') > '00:00'
&& DATE_FORMAT(time, '%H:%i:%s') < '06:00' THEN '00h às 06h'
WHEN DATE_FORMAT(time, '%H:%i:%s') > '06:00'
&& DATE_FORMAT(time, '%H:%i:%s') < '12:00' THEN '06h às 12h'
ELSE 0 END)
as grupos
FROM tb_events
) as acessos
GROUP BY grupos
ORDER BY quantidade;
However, it is not working and returns the error:
Unknown 'num_veh' column in 'field list'
Does anyone know how to fix this problem? Or can you tell me how I could do differently to find a solution?