I have a table that look something like follows
Price | DateTime
--------+-------------
100 | 22/01/2016
210 | 23/01/2016
110 | 24/01/2016
10 | 25/01/2016
20 | 26/01/2016
30 | 13/03/2016
40 | 14/03/2016
50 | 15/03/2016
60 | 16/03/2016
Now we can see there are two date ranges in it:
How can I query my database to get the above results, i.e the data ranges that I have described? The data can be ordered by date but how to get the range
Your ranges appear to be defined by consecutive dates. You can assign the groups by subtracting an increasing number -- via row_number(). The rest is aggregation:
select min(datetime) as range_start, max(datetime) as range_end
from (select t.*,
dateadd(day, - row_number() over (order by datetime), datetime) as grp
from t
) t
group by grp;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With