Álvaro Ruiz
Álvaro Ruiz

Reputation: 239

SQL SERVER - Group records by n minutes interval

I have a table like this:

     [SDate - DateTime]              [Value - Decimal]
    2010-11-16 10:32:22                     1
    2010-11-16 10:58:08                     2

and I need a query to group records by n minutes interval.

Output can be for example(grouped by 60 minutes):

    2010-11-16 10:10:00   avg(Value)
    2010-11-16 10:11:00   avg(Value)
    2010-11-16 10:12:00   avg(Value)

Up to now, I have been using this query to group by 10 minutes interval because intervals were between 0 and 60 minutes:

...
GROUP BY
DATEPART(YEAR, SDate),
DATEPART(MONTH, SDate),
DATEPART(DAY, SDate),
DATEPART(HOUR, SDate),
(DATEPART(MINUTE, SDate) / 10)

But now the interval can be 125436758 minutes, for example.

I can not create new tables and the user-defined interval must be n minutes. I am using SQL SERVER 2012. Thanks.

Upvotes: 2

Views: 7210

Answers (1)

Tab Alleman
Tab Alleman

Reputation: 31785

GROUP BY 
...
(DATEDIFF(MINUTE, 0, SDate) / @n)

Upvotes: 4

Related Questions