我在postgres中有一个带有2列的表格; ordered_timestamp,工作日_小时。
我想创建第三列'due_timestamp',该列是使用'ordered_timestamp'加上'weekday_hours'...但不包括周末(周一至周五12:00至周一12:00)的小时数计算的。
ordered_timestamp | weekday_hours | due_timestamp
2020-06-04 16:00:00 | 12 | 2020-06-05 04:00:00
2020-06-05 16:00:00 | 48 | 2020-06-09 16:00:00
在不排除周末休息时间的情况下,我可以使用ordered_timestamp + interval '1 hour' * weekday_hours
在某些情况下,工作日的小时数可能从1小时到数百小时不等。
这种情况似乎还需要一些其他信息来过滤掉周末时间。
答案 0 :(得分:1)
如果您的日期间隔可能跨越不同的时间段,那么我将使用蛮力方法,通过使用generate_series()
来枚举介于时间戳之间的所有1小时间隔,然后仅计算属于工作日的间隔:
select t.ordered_timestamp, t.due_timestamp, x.weekday_hours
from mytable t
cross join lateral (
select count(*) filter(where extract(dow from ts) between 1 and 5) - 1 weekday_hours
from generate_series(ordered_timestamp, due_timestamp, '1 hour'::interval) s(ts)
) x
ordered_timestamp | due_timestamp | weekday_hours :------------------ | :------------------ | ------------: 2020-06-04 16:00:00 | 2020-06-05 04:00:00 | 12 2020-06-05 16:00:00 | 2020-06-09 16:00:00 | 48
答案 1 :(得分:0)
像这样吗?
case when (EXTRACT(DOW FROM ordered_timestamp ) = 6 )
then ordered_timestamp + interval '1 hour' * (weekday_hours+48)
when (EXTRACT(DOW FROM ordered_timestamp ) = 0 )
then ordered_timestamp + interval '1 hour' * (weekday_hours+24)
else
ordered_timestamp + interval '1 hour' * weekday_hours
end