Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I COUNT the number of rows in a database for different time periods?

I've got a table in a Sybase DB with a column createdDateTime. What I want to be able to do is count how many rows were created between specific but accumulating time periods, ie:
7:00 - 7:15
7:00 - 7:30
7:00 - 7:45
7:00 - 8:00 ... and so on until I have the last time group, 7:00 - 18:00.

Is there a nice way to make one query in SQL that will return all the rows for me with all the row counts:
Time              Rows Created
7:00 - 7:15     0
7:00 - 7:30     5
7:00 - 7:45     8
7:00 - 8:00     15
...                    ...

I have a solution at the moment, but it requires me running a parameterised query 44 times to get all the data.

Thanks,

like image 597
Dhiren Avatar asked Oct 24 '25 18:10

Dhiren


1 Answers

I recently blogged about this exact topic, not sure if it works in Sybase though, here's the solution

declare @interval int
set @interval = 5
select datepart(hh, DateTimeColumn)
, datepart(mi, DateTimeColumn)/@interval*@interval
, count(*)
from thetable
group by datepart(hh, DateTimeColumn)
, datepart(mi, DateTimeColumn)/@interval*@interval

and more details http://ebersys.blogspot.com/2010/12/sql-group-datetime-by-arbitrary-time.html

like image 66
BlackTigerX Avatar answered Oct 26 '25 08:10

BlackTigerX