2

我想根據日期時間列'reading_on'選擇給定日期中每個小時的最新記錄。我執行了下面的查詢如何選擇一天中每小時的最新記錄

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 } 

在上面的查詢中,我沒有得到所需的結果。選擇一天中每小時的最新記錄的正確方法是什麼?下面是表結構

enter image description here

+0

可以提供MySQL表結構,如果可能的話? –

+0

@VishalZanzrukia添加了表結構 – loganathan

+0

是否有任何updated_record_time(Date)字段,我們可以通過該字段獲取小時數據? –

回答

1
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; 
+0

它給出錯誤的答案請參閱http://sqlfiddle.com/#!2/49a69/7 –

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; 

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

+0

它不會返回基於不同年份同一日期的結果。 –

+0

我已編輯答案。 –

+0

請勿複製答案:P –

相關問題