我有如下的PostgreSQL结构和数据:
CREATE TABLE requests (
entity_id INTEGER,
type_de_demande TEXT,
phase TEXT,
time BIGINT,
next_time BIGINT
);
INSERT INTO requests (entity_id, type_de_demande, phase, time, next_time)
VALUES
(3402670, 'SUPPORTREQUEST', 'Log', 1684836635813, 1684836637569),
(3402670, 'SUPPORTREQUEST', 'Classify', 1684836637569, 1684836638257),
(3402670, 'SUPPORTREQUEST', 'FirstLineSupport', 1684836638257, 1685090241035),
(3402670, 'SUPPORTREQUEST', 'Escalate', 1685090241035, 1685090241833),
(3402670, 'SUPPORTREQUEST', 'Close', 1685090241833, NULL)
目标是计算在营业时间(不包括周六和周日)和24x7时间中“time”和“next_time”之间的时间间隔。目前,我能够获得24x7时间的正确间隔,但对于业务间隔,我得到的值不正确。
下面是我的SQL select query:
SELECT
t.entity_id,
t.type_de_demande,
t.phase,
bd.bus_interval,
bd.interval_24x7,
ts.start_ts,
ts.end_ts,
t.time,
t.next_time
FROM requests AS t
inner join lateral (
SELECT
to_timestamp(t.time / 1000)::timestamp AS start_ts,
to_timestamp(t.next_time / 1000)::timestamp AS end_ts,
(SELECT COUNT(*)::int
FROM generate_series(to_timestamp(t.time / 1000)::DATE, to_timestamp(t.next_time / 1000)::DATE, '1 day')
WHERE EXTRACT(ISODOW FROM generate_series) < 6
) AS bus_days
) AS ts ON true
inner join lateral (
SELECT
ts.end_ts - ts.start_ts as interval_24x7,
make_interval(0,0,0,ts.bus_days - 1) + ((ts.end_ts - ts.start_ts)::time)::interval as bus_interval
) as bd on true
结果:
| 实体id|按需类型|相|总线间隔|间隔_24x7|启动ts|端ts|时间|下次|
| - -----|- -----|- -----|- -----|- -----|- -----|- -----|- -----|- -----|
| 三四零二六七零|支持查询|日志|{"秒":2}|{"秒":2}| 2023 - 05 - 23T10:10:35.000Z| 2023 - 05 - 23T10:10:37.000Z| 1684836635813| 1684836637569|
| 三四零二六七零|支持查询|分类|{"秒":1}|[2019 - 04 - 21]| 2023 - 05 - 23T10:10:37.000Z| 2023 - 05 - 23T10:10:38.000Z| 1684836637569| 1684836638257|
| 三四零二六七零|支持查询|一线支持|{"天":3,"小时":22,"分钟":26,"秒":43}|{"天":2,"小时":22,"分钟":26,"秒":43}| 2023 - 05 - 23T10:10:38.000Z| 2023 - 05 - 26T08:37:21.000Z| 1684836638257| 1685090241035|
| 三四零二六七零|支持查询|升级|我的天|我的天|2023 - 05 - 26T08:37:21.000Z| 2023 - 05 - 26T08:37:21.000Z| 1685090241035| 1685090241833|
| 三四零二六七零|支持查询|关闭|零|零|2023 - 05 - 26T08:37:21.000Z|零|1685090241833|零|
为什么bus_interval
列有一个额外的天数{"days":3,"hours":22,"minutes":26,"seconds":43}
,而不是{"days":2,"hours":22,"minutes":26,"seconds":43}
的预期值?是否有其他方法可以计算两个Unix时间戳之间的间隔,同时考虑工作日和24x7时间?
小提琴:https://www.db-fiddle.com/f/axnWR8TUupXywi1ddHDHtX/0
1条答案
按热度按时间of1yzvn41#
我认为你的bus_days子查询应该像下面这样。我已经删除了::DATE转换,并且只在小于或等于www.example.com _time时才包含generate_series timestampt.next。