Detect overlapping date ranges from the same table

前端 未结 9 1143
甜味超标
甜味超标 2020-12-01 04:26

I have a table with the following data

PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
02    15/01/2010         


        
9条回答
  •  旧巷少年郎
    2020-12-01 04:44

    In MySQL you basically need:

    SELECT COUNT(*) FROM date_ranges AS A, date_ranges AS B WHERE A.id <> B.id AND A.id > B.id AND A.end_at > B.start_at AND B.end_at > A.start_at

    > in the second and the third statement can be replaced with >= to follow includes matching.

    This topic is related to the "Allen's Interval Algebra" and there are some more reading on this can be found by those links:

    • http://www.ics.uci.edu/~alspaugh/cls/shr/allen.html
    • http://salman-w.blogspot.com.es/2012/06/sql-query-overlapping-date-ranges.html

提交回复
热议问题