How can we find X
consecutive dates (using by hour
) that meet a condition?
EDIT: here is the SQL fiddle http://sqlfiddle.com/#!17/44928/1
Example:
Find 3 consecutive dates where aa < 2
and bb < 6
and cc < 7
Given this table called weather
:
timestamp | aa | bb | cc |
---|---|---|---|
01/01/2000 00:00 | 1 | 5 | 5 |
01/01/2000 01:00 | 5 | 5 | 5 |
01/01/2000 02:00 | 1 | 5 | 5 |
01/01/2000 03:00 | 1 | 5 | 5 |
01/01/2000 04:00 | 1 | 5 | 5 |
01/01/2000 05:00 | 1 | 5 | 5 |
Answer should return the 3 records from 02:00, 03:00, 04:00
.
How can we do this in Ruby on Rails - or directly in SQL if that is better?
I started working on a method based on this answer: Detect consecutive dates ranges using SQL
def consecutive_dates
the_query = "WITH t AS (
SELECT timestamp d,ROW_NUMBER() OVER(ORDER BY timestamp) i
FROM @d
GROUP BY timestamp
)
SELECT MIN(d),MAX(d)
FROM t
GROUP BY DATEDIFF(hour,i,d)"
ActiveRecord::Base.connection.execute(the_query)
end
But I was unable to get it working.