gpt4 book ai didi

postgresql - Tsrange - 计算两个范围之间的差异

转载 作者:行者123 更新时间:2023-11-29 13:20:07 25 4
gpt4 key购买 nike

我有两个表free_timeappointment。两者都包含 tsranges。

如何编写一个查询(或函数)来确定从 freetime 中“减去”appointment 的差值后的实际空闲时间?

INSERT INTO free_time(freetime)
VALUES('[2017-04-19 09:00, 2017-04-19 12:30)');

INSERT INTO appointment(appointment)
VALUES('[2017-04-19 10:30, 2017-04-19 11:30)');

我希望结果是这样的:

["2017-04-19 9:00","2017-04-19 10:30:00"), 
["2017-04-19 11:30:00","2017-04-19 12:30:00")

最佳答案

您必须拆分范围,从 the docs

The union and difference operators will fail if the resulting range would need to contain two disjoint sub-ranges, as such a range cannot be represented.

为此,您可以使用 lower, and upper

SELECT tsrange(  lower(freetime), lower(appointment)  )  AS before_appointment,
tsrange( upper(appointment), upper(freetime) ) AS after_appointment
FROM ( VALUES
(
'[2017-04-19 09:00, 2017-04-19 12:30)'::tsrange,
'[2017-04-19 10:30, 2017-04-19 11:30)'::tsrange
)
) AS t(freetime,appointment)
WHERE freetime @> appointment;

before_appointment | after_appointment
-----------------------------------------------+-----------------------------------------------
["2017-04-19 09:00:00","2017-04-19 10:30:00") | ["2017-04-19 11:30:00","2017-04-19 12:30:00")
(1 row)

关于postgresql - Tsrange - 计算两个范围之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43502687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com