Monday, March 19, 2012

min/max of x minutes

I am trying to develop a sql statement that will create a recordset of the min (or max) values in x minute increments over a period of time.

e.g. over a period of 7 days, I have data that was collected in 1 minute intervals. I need to know the min (or max) value in each 10 minute interval over that same period of time.

Is there an efficient way of doing this?

Try something like this:

DECLARE @.dt_from DATETIME, @.dt_to DATETIME;
SET @.dt_from = '2006-03-21T00:00:00.000';
SET @.dt_to = '2006-03-28T00:00:00.000';

SELECT MIN(dt) AS dt,
MIN(val) AS min_val, MAX(val) AS max_val
FROM tbl
WHERE dt >= @.dt_from
AND dt < @.dt_to
GROUP BY FLOOR(DATEDIFF(MINUTE,@.dt_from,dt)/10) ;

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--

|||Just recently had a chance to try this out. It worked perfectly. Thanks!

No comments:

Post a Comment