Reputation: 23
First thing, my date format for the field is TIMESTAMP
I have a table that consists of id, domain, hits, when.
Now when I insert the hits into the database, i'm pulling from my analytics API every 10 minutes. So the content of this table is
id=1, domain=test.com, hits=930, when=2011-11-22 16:00:22;
id=2, domain=test2.com, hits=134, when=2011-11-22 16:10:22;
etc
Once this fills up with data every 10 minutes for the last six hours, I want to find the number of hits for each domain for each hour. so:
There will be 6 rows per hour since it inserts every 10 minutes, how can I retrieve the total number of hits for each hour?
If I want to pull my statistics at 1:39PM for the current hour, I should be able to pull all the hits from 1:10PM, 1:20PM, 1:30PM.
DO I need six separate mysql queries that take the current time and run it for each hour because I was be displaying it in a graph (1 hour ago, 2 hours ago, 3 hours ago, etc) or is there a simpler way to achieve this?
Please help me understand, thanks!
Upvotes: 2
Views: 182
Reputation: 7579
You could try
select domain, date_format(when, '%Y-%m-%d %I%p') hour, sum(hits)
from table group by domain, hour
EDIT: I changed the format from %H
for 24 hour clock to %I%p
for 12 hour clock with AM/PM, since it seems like that's what you want.
EDIT2: If it's only the last six hours you want, grouped by how many hours ago the hits were, you might be better off with (added date_format to group by whole hour)
select domain, hour(timediff(date_format(now(), '%Y-%m-%d %H'),
date_format(when, '%Y-%m-%d %H'))) hours, sum(hits)
from table
where hours < 7
group by domain, hours
Upvotes: 2