简体   繁体   English

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

[英]how do I group by day and 2 hrs in postgresql with a “time” field?

I need to group by a day splitting up by 2 hours: 我需要按照一天的时间进行分组,然后将其分为2个小时:

I have used the EXTRACT PostgreSQL function. 我已经使用了EXTRACT PostgreSQL函数。 But couldn't figure out a way to group by 2 hours time 但是无法找到一种方法来按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;

Expected output: 预期产量:

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

like that, I need same for all weekdays 这样的话,我平日都需要

try: 尝试:

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;

like in my sample schema: 就像在我的示例架构中一样:

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

I used epoch(seconds) and then converting into 2 hrs 我使用纪元(秒),然后转换为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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM