如何将间隔时间添加到 postgres 中的时间戳,不包括周末时间

How to add interval hours to a timestamp in postgres, excluding weekend hours

我在 postgres 中有一个 table,有 2 列; ordered_timestamp, weekday_hours.

我想创建第三列 'due_timestamp',它是使用 'ordered_timestamp' 加上 'weekday_hours' 计算的......但不包括周末的时间(12:00am坐到 12:00am 星期一)

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

weekday_hours 在某些情况下可能从 1 小时到数百小时不等。

看来这种情况需要一些额外的东西来过滤周末时间。

是这样的吗?

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

如果您的日期间隔可能跨越不同的时间段,我会使用一种相当蛮力的方法,枚举时间戳与 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

Demo on DB Fiddle:

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