【发布时间】:2017-05-23 12:18:32
【问题描述】:
我有一个包含开始和结束日期的表格:
DROP TABLE temp_period;
CREATE TABLE public.temp_period
(
id integer NOT NULL,
"startDate" date,
"endDate" date
);
INSERT INTO temp_period(id,"startDate","endDate") VALUES(1,'2010-01-01','2010-03-31');
INSERT INTO temp_period(id,"startDate","endDate") VALUES(2,'2013-05-17','2013-07-18');
INSERT INTO temp_period(id,"startDate","endDate") VALUES(3,'2010-02-15','2010-05-31');
INSERT INTO temp_period(id,"startDate","endDate") VALUES(7,'2014-01-01','2014-12-31');
INSERT INTO temp_period(id,"startDate","endDate") VALUES(56,'2014-03-31','2014-06-30');
现在我想知道存储在那里的所有周期的总持续时间。我只需要时间作为interval。这很简单:
SELECT sum(age("endDate","startDate")) FROM temp_period;
但是,问题是:这些时期确实重叠。我想消除所有重叠的时间段,这样我就可以得到表格中至少一条记录所涵盖的总时间。
您知道,时间之间存在相当大的差距,因此将最小的开始日期和最近的结束日期传递给 age 函数将无法解决问题。然而,我想过这样做并减去总的差距,但我没有想到任何优雅的方法。
我使用 PostgreSQL 9.6。
【问题讨论】:
-
输出应该是什么样的?让我们知道您是否必须考虑整个表格才能执行此操作或每个 ID。
-
我只需要
interval的总时间,没有别的 -
您希望它们按 id 还是 startDate 排序?.. 哪一列定义了它们重叠?..
-
我根本不需要订购。开始和/或结束日期使它们重叠,只要存在两个条目的日子。例如 2014-04-01 在 7 和 56 中。
标签: sql postgresql