首页 > 解决方案 > 如何从一个纪元中提取一天中的小时并计算该小时内发生的每个实例?

问题描述

我有一个我觉得很直截了当的问题,但给我带来了一些问题。

我在表 X 中有一个名为的列,event_time它是一个纪元。我想从中提取一天中的时间并计算在那一小时内发生的骑行次数。

所以输出最终将是一个条形图,其中 x 值为 0-24,Y 是发生的实例数(例如骑自行车)。

这是我现在所拥有的,它没有给我正确的输出:

select extract(hour from to_timestamp(start_time)::date) as hr,
count(*) as ct
from x 
group by hr 
order by hr asc

任何提示或帮助表示赞赏。

谢谢

标签: sqlpostgresql

解决方案


您可以使用算术:

select floor( (start_time % (24 * 60 * 60)) / (60 * 60) ) as hour,
       count(*)
from x
group by hour;

或转换为日期/时间并提取小时:

select extract(hour from '1970-01-01'::date + start_time * interval '1 second') as hour, count(*)
from x
group by hour;

推荐阅读