如何在postgresql中按天和2个小时按“时间”字段分组?

时间:2018-08-01 07:04:45

标签: sql postgresql postgresql-10

我需要按照一天的时间进行分组,并划分为2个小时:

我使用了EXTRACT PostgreSQL函数。但是无法找到一种以2小时的时间分组的方法

SELECT EXTRACT(dow from  completed_at) AS "day",
       EXTRACT(hour from  completed_at) AS "hour", count(*)
FROM orders
WHERE completed_at is not null
GROUP BY 1, 2
ORDER BY 1;

预期输出:

day       hour  count
-------- ------ ------
Sun       12am   10
Sun        2am   8
Sun        4am   0
Sun        6am   24
Sun        8am   25
Sun       10am   100
Sun       12pm   67
Sun        2pm   10
Sun        4pm   10
Sun        6pm   10
Sun        8pm   10
Sun       10pm   10

那样,我在所有工作日都需要

2 个答案:

答案 0 :(得分:2)

尝试:

SELECT EXTRACT(dow from  completed_at) AS "day",
       EXTRACT(hour from  completed_at) AS "hour", count(*)
FROM orders
join generate_series(0,22,2) g on g >= extract(hour from completed_at) and g< extract(hour from completed_at) + 2
WHERE completed_at is not null
GROUP BY "day","hour"
ORDER BY 1;

就像在我的示例模式中一样:

db=# create table so (t timestamptz);
CREATE TABLE
Time: 171.144 ms
db=# insert into so select generate_series(now(),current_date + 2,' 1hour'::interval);
INSERT 0 40
Time: 71.150 ms
db=# select count(*), g
from so
join generate_series(0,22,2) g on g >= extract(hour from t) and g< extract(hour from t) + 2
group by g
order by 2,1
;
 count | g
-------+----
     1 |  0
     2 |  2
     2 |  4
     2 |  6
     3 |  8
     4 | 10
     4 | 12
     4 | 14
     4 | 16
     4 | 18
     4 | 20
     4 | 22
     2 | 24
(13 rows)

Time: 11.958 ms

答案 1 :(得分:0)

我使用了纪元(秒),然后转换为2小时

SELECT EXTRACT(dow from  completed_at) AS "Day",
       EXTRACT(hour from  (to_timestamp(floor((extract('epoch' from completed_at) / (60 * 60 * 2) )) * (60 * 60 * 2))
       AT TIME ZONE 'UTC')),
      COUNT(*)
FROM orders
WHERE completed_at is not null
GROUP BY 1, 2
ORDER BY 1;