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

妖精的绣舞 提交于 2019-12-22 11:19:13

问题


I want to select the latest record of each hour in a given date, based on the datetime column 'reading_on'. I have executed the below query

hourly_max =   InverterReading
               .where("DATE(reading_on) = ? AND imei = ?", Date.today, "770000000000126")
               .group("HOUR(reading_on)")
               .having("max(HOUR(reading_on))")

hourly_max.group_by(&:id).each { |k,v| puts v.last.reading_on }

In the above query I am not getting the required result. What is the proper way to select the latest record of each hour in a day. Below is the table structure


回答1:


SELECT 
   HOUR(a.reading_on) As hr, max(a.id),a.reading_on
FROM 
   InverterReadings a
LEFT JOIN
   InverterReadings b
ON
        YEAR(a.reading_on)=YEAR(b.reading_on)
        AND MONTH(a.reading_on)=MONTH(b.reading_on)
        AND day(a.reading_on)=day(b.reading_on)
        AND hour(a.reading_on)=hour(b.reading_on)
AND 
    a.reading_on < b.reading_on
WHERE 
    b.reading_on is null
group by a.reading_on;

Demo : http://sqlfiddle.com/#!2/49a69/14




回答2:


SELECT 
   HOUR(a.reading_on) As hr, max(a.id),a.reading_on,
date_format(a.reading_on,'%j-%Y-%k')
FROM 
   InverterReadings a
LEFT JOIN
   InverterReadings b
ON
      date_format(a.reading_on,'%j-%Y-%k') = date_format(b.reading_on,'%j-%Y-%k')
AND 
    a.reading_on < b.reading_on
WHERE 
    b.reading_on is null
group by a.reading_on;


来源:https://stackoverflow.com/questions/23707871/how-to-select-the-latest-record-of-each-hour-in-a-day

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!