如何在单个中合并重叠日期

时间:2013-01-25 15:25:00

标签: oracle oracle10g oracle11g

如何从同一个表中的两个重叠日期行中获取相同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

谢谢。 瑞木

1 个答案:

答案 0 :(得分: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

这是Fiddle

祝你好运。