SQL Server: Sum of values for Time Slots

Who is online?  106 guests and 0 members
home  »  articles  »  SQL Server: Sum of values for Time Slots

SQL Server: Sum of values for Time Slots

change text size: A A A
Published: 4/5/2011 2:33:24 PM by  Sachin Nandanwar  - Views:  [5635]

I had a bit of an unusual task where I needed to find the sum of values in between specific time interval slot for dates.Below is a small sample of the data.Here I need to find the sum of values for slots of 5 minutes.This is what I came up with.

Sample Data and Query

Declare @t table(value int,dt datetime)
insert  @t
select 1,'01-01-1900 12:45:00' union all
select 5,'01-01-1900 12:48:00' union all
select 3,'01-01-1900 12:03:00' union all
select 6,'01-01-1900 12:02:00' union all
select 8,'01-01-1900 12:07:00'

declare @slot int=5

select
SUM(value)SumOfSlots,CONVERT(varchar(20),dateadd(minute,(datediff(minute,0,dt)/@slot*@slot),0),108) + ' -- '+ CONVERT(varchar(20),dateadd(mi,5,dateadd(minute,(datediff(minute,0,dt)/@slot*@slot),0)),108)Range
from @t group by
CONVERT(varchar(20),dateadd(minute,(datediff(minute,0,dt)/@slot*@slot),0),108) + ' -- '+ CONVERT(varchar(20),dateadd(mi,5,dateadd(minute,(datediff(minute,0,dt)/@slot*@slot),0)),108)

I have set the time slot as 5 minutes.You can replace it with 10,15 etc to test it.Let me know your thoughts on this.

  To rate this article please  register  or  login

Author

Sachin Nandanwar Sachin Nandanwar (Member since: 3/14/2011 4:21:32 PM)

Comments (1)

Maurice.Pelchat
8/30/2011 4:17:59 PM Maurice Pelchat said:

To improve query apparence and readability I would suggest this trick you probably already knows.  It avoid repeating complex expressions and cost nothing more from a performance standpoint.

With TS 
as 
(
select 
  value 
, CONVERT(varchar(20),dateadd(minute,(datediff(minute,0,dt)/@slot*@slot),0),108) + ' -- '
+ CONVERT(varchar(20),dateadd(mi,5,dateadd(minute,(datediff(minute,0,dt)/@slot*@slot),0)),108) as Range
from @t 
)
Select Sum(Value) as SumOfSlot, range 
From TS
group by 
  range
  

by

Leave a comment

Name:
  *  
Email:  (your email is kept secure)
 *  
Website:

example: "http://www.SQLServerGeeks.com"

 
Type the characters:
 *
 
   

Training on Microsoft Products & Technologies

Email Subscriptions

   Get the Most Recent Blogs in your inbox
Articles RSS Feed

Most Recent Articles