如何在SQL中找到没有间隙的最长时间段?

时间:2012-07-04 11:07:31

标签: sql tsql gaps-and-islands

  

可能重复:
  SQL: finding longest date gap

我有一张以下结构表:

| LearnerId | FirstName | LastName |  EnrollmentDate  | CompletionDate |

我需要使用SQL查询,在没有注册或完成学习者的情况下获得学校最长的学习时间。我该怎么做?

1 个答案:

答案 0 :(得分:1)

我假设您可以访问CTE和ROW_NUMBER()

首先,您需要一个有序的日期列表。也就是说,不是两列,而是一列。然后,您可以非常简单地将一个日期与下一个日期进行比较。

由于您有两列中的数据,因此创建此一个有序列表将相对昂贵。我希望你没有大量的数据。

WITH
  all_dates
AS
(
  SELECT EnrolmentDate  AS event_date FROM yourTable GROUP BY EnrolmentDate
  UNION
  SELECT CompletionDate AS event_date FROM yourTable GROUP BY CompletionDate
)
,
  sequenced_dates
AS
(
  SELECT
    ROW_NUMBER() OVER (ORDER BY event_date) AS id,
    event_date
  FROM
    all_dates
)
SELECT
  MAX(DATEDIFF(DAY, first_event.event_date, second_event.event_date)) AS duration
FROM
  sequenced_dates    AS first_event
INNER JOIN
  sequenced_dates    AS second_event
    ON first_event.id = second_event.id - 1