Microsoft SQL Server 2012 - Count records by hour with a start and end time stamp -
i trying build query counts how many records there in hour.
my tablet has following columns:
sessionid, created, sessionstart, sessionend
the session time stamps contain date , time. example: 2012-09-07 05:11:08.150
the goal of query return example column called hour , column called total total sum of records within hour start , end.
i not know if possible or not.
thanks!
this query return totals each session active during beginning of each hour have data for:
-- load test data; sessions starting 9-5 lasting 3 hours declare @yourtable table ( sessionid int identity(1,1), sessionstart datetime, sessionend datetime ) while (select count(*) @yourtable) < 1000 begin insert @yourtable(sessionstart) values(dateadd(minute,round(rand()*480,0),'2014-03-24 09:00')) end update @yourtable set sessionend = dateadd(minute,round(rand()*360,0),sessionstart) -- create hour table based on min/max sessionstart/end values declare @hour table(boh datetime,eoh datetime) -- begin of hour, end of hour insert @hour(boh) select dateadd(hour,datediff(hour,0,min(sessionstart)),0) @yourtable while (select max(boh) @hour) < (select max(sessionend) @yourtable) begin insert @hour(boh) select dateadd(hour,1,max(boh)) @hour end update @hour set eoh = dateadd(hour,1,boh) -- return results sessions active during each hour select h.boh [hour], count(t.sessionid) total @yourtable t inner join @hour h on t.sessionstart < h.eoh , t.sessionend >= h.boh group h.boh
Comments
Post a Comment