Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate data by hour based on Timestamp

Tags:

mysql

This must be a common thing to want to do, but I'm stuck.

I have some data that could be simplified like this:

id    user    unixtime
-----------------------
1     dave    1335312057
2     dave    1335312058
3     steve   1335312128

etc.

So far, I have only needed to aggregate by day, so I've been using:

SELECT
 UNIX_TIMESTAMP(DATE(FROM_UNIXTIME(unixtime))) AS time,
 count(c.user) AS count
FROM core c
GROUP BY DATE(FROM_UNIXTIME(unixtime))

I've tried using CONCAT with DATE and HOUR, but can't quite get it working as expected – any ideas?

like image 292
Rich Bradshaw Avatar asked Oct 27 '12 19:10

Rich Bradshaw


1 Answers

SELECT
 DATE(FROM_UNIXTIME(unixtime)) as date,
 HOUR(FROM_UNIXTIME(unixtime)) AS hour,
 count(c.user) AS count
FROM core c
GROUP BY 1,2 

if you want the hour as a unix timestamp, wrap this query to get it:

SELECT UNIX_TIMESTAMP(DATE_ADD(the_date, INTERVAL the_hour HOUR)), the_count
from (select
    DATE(FROM_UNIXTIME(unixtime)) as the_date,
    HOUR(FROM_UNIXTIME(unixtime)) as the_hour,
    count(c.user) AS the_count
    FROM core c
    GROUP BY 1,2 
) x

Note: Used the_ prefix on column names to avoid problems with reserved words

like image 122
Bohemian Avatar answered Oct 29 '22 20:10

Bohemian