如何按时间段(例如小时)选择每个用户的计数?

时间:2015-04-03 20:21:52

标签: sql postgresql select postgresql-9.2

如何编写Postgresql查询以按小时查找用户的计数?

表:

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

期望的输出:

        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

我试过这个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;

但它给了我:

 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 |

类似:

4 个答案:

答案 0 :(得分:3)

select
    date_trunc('hour', "date") as "hour",
    name,
    count(*) as "count"
from my_table
group by 1, 2
order by 1, 3 desc;

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

答案 1 :(得分:3)

如果你想坚持使用窗口功能,你需要添加" name"进入你的列表:

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

答案 2 :(得分:1)

这对我有用:http://www.sqlfiddle.com/#!12/a50d4/57

SELECT DISTINCT name,
                date_trunc('hour', date) as hour,
                count(*) as count
FROM my_table
GROUP BY name, hour
ORDER BY hour, count DESC;

答案 3 :(得分:0)

我认为你正在寻找这个

SELECT DISTINCT
       date_trunc('hour', "date") AS hour,
       name,
       count(*) as tcount
FROM my_table
GROUP BY  hour,name
ORDER BY  hour, count(*) Desc

<强>输出:

        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

SQLFIDDLE