问题
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