Mysql – How to select the latest record of each hour in a day

MySQLmysql-5

I want to select the latest record of each hour in a given date, based on the datetime column 'reading_on' in my table. What is the best way to do it? I already tried group by HOUR(reading_on) with HAVING("max(HOUR(reading_on))"), but I didn't get the proper result.

Below is my table structure

enter image description here

Best Answer

That's a groupwise maximum.
You may plump for a null-self-join:

SELECT  ir1.*
FROM inverter_readings IR1
LEFT JOIN inverter_readings IR2 ON
DATE(IR1.READING_ON) = DATE(IR2.READING_ON) AND
HOUR(IR1.READING_ON) = HOUR(IR2.READING_ON) AND
IR1.READING_ON  < IR2.READING_ON
WHERE IR2.id IS NULL

sqlfiddle demo.