返回重叠日期时间记录

时间:2015-09-25 03:54:54

标签: sql sql-server-2008

我正在尝试获取Number相等的记录,而下一行的StartTimeless than第一行的EndTime,但是{{1是不同的。

这是我正在使用的表格。

enter image description here

这是我想要获得的输出:

enter image description here

这是我到目前为止所提出的。 (此查询返回额外的行)

UID

SQLFIDDLE DEMO

有关我如何修复此查询的任何建议?

2 个答案:

答案 0 :(得分:1)

SELECT * 
FROM   calls 
WHERE  number IN (SELECT r1.number 
                  FROM   calls r1 
                         CROSS JOIN calls r2 
                  WHERE  r2.starttime < r1.endtime 
                         AND r1.number = r2.number 
                  GROUP  BY r1.number 
                  HAVING Count(1) > 1) 

答案 1 :(得分:0)

您可以使用LAG / LEAD获取上一个/下一个记录数据:

<强> SqlFiddleDemo

;WITH CTE AS
(
  SELECT
    ID
    ,UID
    ,NUMBER
    ,StartTime
    ,EndTime
    ,LAG(EndTime) OVER(PARTITION BY Number ORDER BY StartTime) AS PrevEndTime
    ,LAG(UID) OVER(PARTITION BY Number ORDER BY StartTime) AS PrevUID
    ,(SELECT COUNT(Number) FROM CALLS c1 WHERE  c1.Number = c.Number)  AS Counter
  FROM CALLS c
)
SELECT
     ID
    ,UID
    ,NUMBER
    ,StartTime
    ,EndTime
FROM CTE
WHERE (StartTime < PrevEndTime OR PrevEndTime IS NULL)
  AND (PrevUID <> UID OR PrevUID IS NULL)
  AND Counter > 1
ORDER BY ID;