作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
预订表包含预订开始日期、开始时间和持续时间。开始时间在工作日的工作时间 8:00 .. 18:00 以半小时为增量。持续时间也以一天中的半小时为增量。
CREATE TABLE reservation (
startdate date not null, -- start date
starthour numeric(4,1) not null , -- start hour 8 8.5 9 9.5 .. 16.5 17 17.5
duration Numeric(3,1) not null, -- duration by hours 0.5 1 1.5 .. 9 9.5 10
primary key (startdate, starthour)
);
如果需要,可以更改表结构。
如何在未预留的表中找到第一个空闲半小时?E.q 如果表包含
startdate starthour duration
14 9 1 -- ends at 9:59
14 10 1.5 -- ends at 11:29, e.q there is 30 minute gap before next
14 12 2
14 16 2.5
结果应该是:
starthour duration
11.5 0.5
大概应该用PostgreSql 9.2的窗口函数来查找starthour 大于上一行 starthour + duration 的第一行
如何编写返回此信息的 select 语句?
最佳答案
Postgres 9.2 有范围类型,我建议使用它们。
create table reservation (reservation tsrange);
insert into reservation values
('[2012-11-14 09:00:00,2012-11-14 10:00:00)'),
('[2012-11-14 10:00:00,2012-11-14 11:30:00)'),
('[2012-11-14 12:00:00,2012-11-14 14:00:00)'),
('[2012-11-14 16:00:00,2012-11-14 18:30:00)');
ALTER TABLE reservation ADD EXCLUDE USING gist (reservation WITH &&);
“EXCLUDE USING gist”创建不允许插入重叠条目的索引。您可以使用以下查询来查找间隙(vyegorov 查询的变体):
with gaps as (
select
upper(reservation) as start,
lead(lower(reservation),1,upper(reservation)) over (ORDER BY reservation) - upper(reservation) as gap
from (
select *
from reservation
union all values
('[2012-11-14 00:00:00, 2012-11-14 08:00:00)'::tsrange),
('[2012-11-14 18:00:00, 2012-11-15 00:00:00)'::tsrange)
) as x
)
select * from gaps where gap > '0'::interval;
“联合所有值”掩盖了非工作时间,因此您只能在上午 8 点到晚上 18 点之间进行预订。
结果如下:
start | gap
---------------------+----------
2012-11-14 08:00:00 | 01:00:00
2012-11-14 11:30:00 | 00:30:00
2012-11-14 14:00:00 | 02:00:00
文档链接:- http://www.postgresql.org/docs/9.2/static/rangetypes.html “范围类型”- https://wiki.postgresql.org/images/7/73/Range-types-pgopen-2012.pdf
关于sql - 如何在 PostgreSql 的预订表中找到第一个空闲时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13387189/
我是一名优秀的程序员,十分优秀!