在SQL中查找重叠日期

时间:2011-01-24 19:12:04

标签: sql ruby-on-rails

每个注册都有一个start_date和end_date。如何以任何方式找到与另一个重叠的注册。

谢谢!

4 个答案:

答案 0 :(得分:2)

重叠测试的正确答案是This.StartOther.End的两倍,如此处所述http://c2.com/cgi/wiki?TestIfDateRangesOverlap

WHERE A.start < B.end
  AND B.start < A.end

如果您认为“触摸”日期为重叠,请将<更改为<=,例如

Jan1 - Jan13
Jan13 - Jan15

返回<=的重叠但<

不重叠

答案 1 :(得分:1)

这只是一个SQL问题......我认为这个SQL会为你做这件事:

select r1.* 
from registrations r1, registrations r2
where 
  r1.start_date < r2.start_date
  and r1.end_date > r2.start_date

在Rails中你会这样做:

registrations = Registration.find_by_sql(sql)

其中sql等于上面的sql代码。

答案 2 :(得分:0)

这会找到两个范围之间任何重叠的任何范围1,即使其中一个未完全包含在另一个范围内。

select r1.* 
 from registrations r1
 JOIN registrations r2 ON r1.start_date 
                  between r2.start_date
                      AND r2.end_date

答案 3 :(得分:0)

标准SQL有一个OVERLAPS运算符。

CREATE TABLE over_laps
(
  start_date date NOT NULL,
  end_date date NOT NULL,
  CONSTRAINT over_laps_pkey PRIMARY KEY (start_date, end_date),
  CONSTRAINT over_laps_check CHECK (start_date < end_date)
)


insert into over_laps values
('2011-01-10', '2011-01-15'), 
('2011-01-08', '2011-01-09'),
('2011-01-09', '2011-01-10'),
('2011-01-09', '2011-01-11'),
('2011-01-10', '2011-01-12'),
('2011-01-11', '2011-01-13'),
('2011-01-13', '2011-01-15'),
('2011-01-14', '2011-01-16'),
('2011-01-15', '2011-01-17'),
('2011-01-17', '2011-01-19');

select t1.start_date start_1, t1.end_date end_1, 
       t2.start_date start_2, t2.end_date end_2
from over_laps t1
inner join over_laps t2 
  on ((t1.start_date, t1.end_date) overlaps (t2.start_date, t2.end_date))
-- Exclude rows that overlap themselves, a trivial case in a self-joined table.  
where t1.start_date <> t2.start_date and 
      t1.end_date   <> t2.end_date