Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Calculating Hourly Totals....

Author  Topic 

mitin
Yak Posting Veteran

81 Posts

Posted - 2013-01-16 : 09:56:21
Hi, I have the below query:


SELECT distinct servername, eventid,
DATEPART(hour, slastoccurrence) AS HourOfDay,
DATEADD(dd,DATEDIFF(dd,0,slastoccurrence),0) AS Date,
SUM(tally) AS NumberOfEvents,
SUM(COUNT(*)) OVER(PARTITION BY DATEADD(dd,DATEDIFF(dd,0,slastoccurrence),0)) as DayTotal,
SUM(COUNT(*)) OVER(PARTITION BY servername, DATEADD(dd,DATEDIFF(dd,0,slastoccurrence),0)) as DayTotalByServer

FROM datatable
WHERE
sfirstoccurrence >= '2012-11-21' and sfirstoccurrence < '2012-11-22' and
slastoccurrence >= '2012-11-21'
AND slastoccurrence < '2012-11-22'
GROUP BY
servername,
eventid,
DATEPART(hour, slastoccurrence),
DATEADD(dd,DATEDIFF(dd,0,slastoccurrence),0)
order by hourofday


This query gives an individual total for each "eventID" within each hour, but I would like to simplify it to give a total "NumberOfEvents" within each hour....I'm no longer interested in the total for each individual event id....

Not sure how to do this, can anyone help please?

Thanks

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2013-01-16 : 10:05:37
Try removing eventid from select column list AND from group by clause...


Too old to Rock'n'Roll too young to die.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-01-16 : 23:43:18
the distinct in select doesnt make any sense as you're already grouping so please remove it

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

mitin
Yak Posting Veteran

81 Posts

Posted - 2013-01-17 : 04:34:33
Thanks guys I removed eventid from the select and group by clause and that worked :)

also, I removed the distinct, thanks.

A step further... if I wanted to get a total for every 5 minutes rather than an hour, anyone know how I would do this?

Thanks
Go to Top of Page

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-01-17 : 04:39:17
Add a column in the select list and add also to the grouping:
DATEADD(mi,DATEDIFF(mi,0,slastoccurrence)/5*5,0)
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-01-17 : 04:42:28
see generic function i created for similar scenarios

http://visakhm.blogspot.in/2010/02/aggregating-data-over-time-slots.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -