具有重叠天数的每小时和每天组11:00 pm-1:00 am

问题描述

我正在尝试计算在给定的每小时窗口和一天内活动的 ID 数量我有三列:start_time、end_time 和 id。

大多数组是标准的当天分组,即上午 9 点至上午 11 点、上午 11 点至下午 1 点等。

其中一个分组重叠两天(晚上 11 点到凌晨 1 点)。也就是说,5 月 16 日 11:01 PM 和 5 月 17 日 12:01 AM 应该在同一组中。但是,在编写简单查询时,您最终会将 5 月 17 日上午 12:01 分组到 5 月 17 日晚上 11:00 之内。

我已经尝试了几个查询,其中包含 case 语句和子查询的几种变体,但无法获得要点。

以下查询尝试为 11pm_1am 列提供了 0。我想我可以将上午 12:30 的时间移到前一个日期并在那里计数,但没有运气。

select date_trunc('day',start_time_1) as date_active,count(distinct(case when CAST(start_time_1 AS TIME) <= '06:00:00' and CAST(end_time_1 AS TIME) >= '01:00:00' then id end)) as early_morning,count(distinct(case when CAST(start_time_1 AS TIME) <= '00:00:00' and CAST(end_time_1 AS TIME) >= '23:00:00' then id end)) as overnight_11pm_1am
from 
(select id,case 
when cast(start_time as time) between '00:00:00' and '01:00:00' 
then start_time - INTERVAL '01:00' HOUR TO MINUTE 
else start_time 
end as start_time_1,case 
when cast(end_timeas time) between '00:00:00' and '01:00:00' 
then end_time - INTERVAL '01:00' HOUR TO MINUTE 
else end_time 
end as end_time_1
from table
where start_time >= '2021-01-01'
and  start_time < '2021-01-04'
)
group by date_active

没有想法。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)