I need to group data in intervals of 15 (or X) minutes in sql.
For example, i have the next scenario.
The result that i expect to obtain is
I tried using Lag function but i dont get what i want, because it add interval to each row and continues grouping.
Thanks in advance and apologies for my bad english.
Advertisement
Answer
If you want the intervals to be calendar based — i.e. four per hour starting at 0, 15, 30, and 45 minutes, then you can use:
select id, min(begin_date), max(begin_date) from t group by id, convert(date, begin_date), datepart(hour, begin_date), datepart(minute, begin_date) / 15;
Note that begin date and end date have the same value, so I just used begin_date
in this answer.