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

Tsrange - Calculating the difference between two ranges

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

如何编写一个查询(或函数)来确定 "subtracting" appointmentfreetime 之后的实际空闲时间?

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)