[英]In SQL: How to find two date values where the second one starts when the first one finishes?
I am trying to run an SQL query to find (and unite) two entries of dates where the second date starts after a short term, eg x, after the first date ends. 我正在尝试运行一个SQL查询来查找(和联合)两个日期条目,其中第二个日期在短期后开始,例如x,在第一个日期结束后。
The data in my table consists (among other columns) of two date columns: added and removed. 我的表中的数据包括(在其他列中)两个日期列:添加和删除。 I am comparing the entries with a copy of the table Joined with the original
我正在将条目与表格的副本进行比较
SELECT *
FROM table
LEFT JOIN table AS table2 ON table.id=table2.id AND table.removed<table2.added
With this code, I can get all the entries that don't overlap each other. 使用此代码,我可以获得彼此不重叠的所有条目。 How can I add another criteria to define a peroid x that only gives me the not overlapping dates which are inside a range of x.
如何添加另一个标准来定义一个peroid x,它只给出了x范围内不重叠的日期。 So something like " table2.removed - table.added <= x".
所以像“table2.removed - table.added <= x”。
Best would be to unite these rows to one if the above critera fits. 如果上面的critera适合,最好将这些行合并为一。
EDIT: sample table data and the result 编辑:样本表数据和结果
id added removed
1 2009-03-11 23:27:58 2017-01-28 04:45:20
1 2017-01-31 05:07:10 2018-01-22 14:14:11
So eg I want to detect this row with x < 5 days. 所以例如我想在x <5天内检测到这一行。
Date functions are notoriously database specific. 众所周知,日期函数是特定于数据库的。 But here is the idea using standard syntax:
但这是使用标准语法的想法:
SELECT *
FROM table t LEFT JOIN
table t2
ON t.id = t2.id AND
t2.added > t.remove and
t2.added < t.remove + interval '5 day' -- whatever value you want
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.