Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select count of each user by time period (e.g., hour)?

How do I write a Postgresql query to find the counts for users by hour?

Table:

date                 name
-------------------  ----
2015-01-01 23:11:11  John
2015-02-02 23:22:22  John
2015-02-02 23:00:00  Mary
2015-02-02 23:59:59  Mary
2015-03-03 00:33:33  Mary

Desired output:

        hour         | name    | count
---------------------+---------+-------
 2015-01-01 23:00:00 | John    |     1
 2015-02-02 23:00:00 | Mary    |     2
 2015-02-02 23:00:00 | John    |     1
 2015-03-03 00:00:00 | Mary    |     1

I tried this http://www.sqlfiddle.com/#!12/a50d4/2:

CREATE TABLE my_table (
    date TIMESTAMP WITHOUT TIME ZONE,
    name TEXT
);
INSERT INTO my_table (date, name) VALUES ('2015-01-01 23:11:11', 'John');
INSERT INTO my_table (date, name) VALUES ('2015-02-02 23:22:22', 'John');
INSERT INTO my_table (date, name) VALUES ('2015-02-02 23:00:00', 'Mary');
INSERT INTO my_table (date, name) VALUES ('2015-02-02 23:59:59', 'Mary');
INSERT INTO my_table (date, name) VALUES ('2015-03-03 00:33:33', 'Mary');

SELECT DISTINCT
       date_trunc('hour', "date") AS hour,
       name,
       count(*) OVER (PARTITION BY date_trunc('hour', "date")) AS count
FROM my_table
ORDER BY hour, count;

but it gives me:

 hour                | name | count |
---------------------|------|-------|
 2015-01-01 23:00:00 | John |     1 |
 2015-02-02 23:00:00 | Mary |     3 |
 2015-02-02 23:00:00 | John |     3 |
 2015-03-03 00:00:00 | Mary |     1 |

Similar:

  • Select distinct users group by time range
  • PostgreSQL: running count of rows for a query 'by minute'
like image 330
Rob Bednark Avatar asked Oct 19 '25 15:10

Rob Bednark


1 Answers

If you want to stick with the window functions, you need to add "name" into your list like this:

http://www.sqlfiddle.com/#!12/a50d4/51

SELECT DISTINCT
   date_trunc('hour', "date") AS "hour",
   name,
   count(name) OVER (PARTITION BY name, date_trunc('hour', "date")) AS "cnt"
FROM my_table
ORDER BY hour, cnt DESC
like image 118
Bob Avatar answered Oct 21 '25 06:10

Bob