简体   繁体   English

使用SQL查找重叠间隔

[英]Finding overlapping intervals using SQL

I want to extract rows from a table whose interval intersects with an interval specified in the query. 我想从一个表中提取行,该表的间隔与查询中指定的间隔相交。 Assuming that I have a simple ID, DATE_START, DATE_END table and two query parameters P_DATE_START and P_DATE_END , what is the simplest way of expressing the query so that I find all rows for which [DATE_START, DATE_END] has at least one common element with [P_DATE_START, P_DATE_END] ? 假设我有一个简单的ID, DATE_START, DATE_END表和两个查询参数P_DATE_STARTP_DATE_END ,表达查询的最简单方法是什么,以便找到[DATE_START, DATE_END]至少有一个公共元素的所有行[P_DATE_START, P_DATE_END]


Update: 更新:

To make the desired outcome clearer, please find a list of input values and expected outcomes below. 为了使预期结果更清晰,请在下面找到输入值和预期结果的列表。 Colums are DATE_START, DATE_END, P_DATE_START, P_DATE_END, MATCH . Colums为DATE_START, DATE_END, P_DATE_START, P_DATE_END, MATCH

16, 17, 15, 18, YES
15, 18, 16, 17, YES
15, 17, 16, 18, YES
16, 18, 15, 17, YES
16, 17, 18, 19, NO
18, 19, 16, 17, NO

Even simpler: 更简单:

SELECT id, date_start, date_end 
FROM thetable 
WHERE date_start <= p_date_end 
AND date_end >= p_date_start

Depending on your dbms, you might be able to use the OVERLAPS operator. 根据您的dbms,您可以使用OVERLAPS运算符。

select * from your_table
where (date '2011-01-15', date '2011-01-18') overlaps (date_start, date_end)

SELECT id,date_start,date_end FROM thetable WHERE not(date_end <p_date_start OR p_date_end <date_start)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM