-5

我如何从同一个表的两个重叠日期行中为相同的 id 获取一行。我有超过 50000 条记录。

我有以下示例数据。

ID    start_dt    end_dt       division
1212  04/01/2006  03/01/2007   second
1212  05/01/2009  01/01/2010   second
1212  04/01/2006  03/01/2008   second   --- This should be selected as longest timeframe
1212  09/03/2007  03/01/2008   third
1213  05/03/2005  04/11/2009   second
1214  07/03/2007  03/01/2008   third

我应该得到的数据如下。

ID    start_dt    end_dt       division
1212  04/01/2006  03/01/2008   second
1212  05/01/2009  01/01/2010   second
1213  05/03/2005  04/11/2009   second
1214  07/03/2007  03/01/2008   third

谢谢你。拉姆

4

1 回答 1

0

现在我了解了您的问题,只需减去 2 个日期即可确定时间范围差异:

SELECT S.Id, S.Start_dt, S.End_dt, S.Division
FROM Sample S
 JOIN (
   SELECT S.Id, Max(S.end_dt-S.start_dt) as timeframe
FROM Sample S
GROUP BY S.Id ) S2 ON S.Id = S2.Id 
    AND S.end_dt-S.start_dt = s2.timeframe

这是小提琴

祝你好运。

于 2013-01-25T15:40:13.390 回答