Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
726 views
in Technique[技术] by (71.8m points)

tsql - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
GROUP BY 
...
(DATEDIFF(MINUTE, 0, SDate) / @n)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...