我正在使用 PostgreSQL 8.3.8。
我在 time_boundaries 表中有一个时间边界列表(按日期):
CREATE TABLE role_times_boundaries
(
role_date DATE,
time_boundary TIME
);
INSERT INTO role_times_boundaries (role_date, time_boundary) VALUES ('2013-04-24'::date, '09:00:00'::time);
INSERT INTO role_times_boundaries (role_date, time_boundary) VALUES ('2013-04-24'::date, '10:00:00'::time);
INSERT INTO role_times_boundaries (role_date, time_boundary) VALUES ('2013-04-25'::date, '07:00:00'::time);
INSERT INTO role_times_boundaries (role_date, time_boundary) VALUES ('2013-04-25'::date, '08:50:00'::time);
INSERT INTO role_times_boundaries (role_date, time_boundary) VALUES ('2013-04-25'::date, '09:00:00'::time);
INSERT INTO role_times_boundaries (role_date, time_boundary) VALUES ('2013-04-25'::date, '12:00:00'::time);
INSERT INTO role_times_boundaries (role_date, time_boundary) VALUES ('2013-04-25'::date, '13:00:00'::time);
INSERT INTO role_times_boundaries (role_date, time_boundary) VALUES ('2013-04-25'::date, '16:00:00'::time);
INSERT INTO role_times_boundaries (role_date, time_boundary) VALUES ('2013-04-25'::date, '17:30:00'::time);
INSERT INTO role_times_boundaries (role_date, time_boundary) VALUES ('2013-04-25'::date, '20:00:00'::time);
所以,我有这个表格内容:
role_date | time_boundary
------------+---------------
2013-04-24 | 09:00:00
2013-04-24 | 10:00:00
2013-04-25 | 07:00:00
2013-04-25 | 08:50:00
2013-04-25 | 09:00:00
2013-04-25 | 12:00:00
2013-04-25 | 13:00:00
2013-04-25 | 16:00:00
2013-04-25 | 17:30:00
2013-04-25 | 20:00:00
目标
我想通过将每个 time_boundary 作为“start_time”和下一个 time_boundary(按顺序)在同一日期对“role_times_boundaries”进行自我内连接来构建一个“时间片列表”表。目标是得到这样的结果:
role_date | start_time | end_time
------------+------------+----------
2013-04-24 | 09:00:00 | 10:00:00
2013-04-25 | 07:00:00 | 08:50:00
2013-04-25 | 08:50:00 | 09:00:00
2013-04-25 | 09:00:00 | 12:00:00
2013-04-25 | 12:00:00 | 13:00:00
2013-04-25 | 13:00:00 | 16:00:00
2013-04-25 | 16:00:00 | 17:30:00
2013-04-25 | 17:30:00 | 20:00:00
暂定的
我试图通过这个 SQL 查询得到想要的结果
SELECT role_times_boundaries.role_date,
role_times_boundaries.time_boundary AS start_time,
end_time_boundaries.time_boundary AS end_time
FROM role_times_boundaries
INNER JOIN (
SELECT role_date,
time_boundary
FROM role_times_boundaries
) AS end_time_boundaries ON (
role_times_boundaries.role_date = end_time_boundaries.role_date
AND end_time_boundaries.time_boundary = (
SELECT MIN(a_list_of_end_boundaries.time_boundary)
FROM role_times_boundaries AS a_list_of_end_boundaries
WHERE a_list_of_end_boundaries.time_boundary > role_times_boundaries.time_boundary
)
)
结果如下:
role_date | start_time | end_time
------------+------------+----------
2013-04-24 | 09:00:00 | 10:00:00
2013-04-25 | 07:00:00 | 08:50:00
2013-04-25 | 08:50:00 | 09:00:00
2013-04-25 | 12:00:00 | 13:00:00
2013-04-25 | 13:00:00 | 16:00:00
2013-04-25 | 16:00:00 | 17:30:00
2013-04-25 | 17:30:00 | 20:00:00
如果你看得很清楚, 09:00: 00 到 12:00:00的时间片丢失了!但我仍然不明白为什么,仍然没有找到我的错误。