在此示例中写入重叠时间的查询

时间:2015-06-02 05:05:37

标签: mysql sql-server tsql

想象一下,我有一张包含以下数据的表格: enter image description here

我想写一个查询,给出: 有重叠时间的客户,例如:

Row 2,3
because customer of these are the same and the overlapping time

2 个答案:

答案 0 :(得分:1)

以下是使用SELF-JOIN的方法。对于大型表格而言,这可能效率不高:

SELECT t1.* 
FROM TestData t1
INNER JOIN TestData t2
    ON t2.Customer = t1.Customer
    AND t2.EndDate >= t1.StartDate
    AND t2.StartDate <= t1.EndDate
    AND t1.Row <> t2.Row

SQL Fiddle

答案 1 :(得分:0)

SELECT a.Row
      ,a.customer
      ,a.start
       ,a.end
      ,b.ColumnId AS OverlappedId 
      ,b.InTime   AS OverlappedInTime 
      ,b.OutTime  AS OverlappedOutTime 
  FROM Time  AS a 
  JOIN Time  AS b ON ((a.start BETWEEN b.start AND b.end) 
                       OR  (a.end BETWEEN b.start AND b.end)) 
                      AND  (a.row!= b.row)