CREATE TABLE tmp_end_date(ID INT,tgs_rec_eff_dt DATE)GO
insert into tmp_end_date values(1300505,'2012-08-01 15:57:15')insert into tmp_end_date values(1300505,'2012-08-01 15:55:16')insert into tmp_end_date values(1300505,'2012-07-30 11:29:34')insert into tmp_end_date values(1300505,'1905-07-01')GO
WITH aa AS(SELECT ID,tgs_rec_eff_dt FROM tmp_end_date)SELECT ROW_NUMBER()over(partition by ID order by tgs_rec_eff_dt) rownumber, ID, tgs_rec_eff_dt, NULL as end_date ---populate based on start date of next record - 1FROM aa
CREATE TABLE tmp_end_date(ID INT,tgs_rec_eff_dt DATETIME);INSERT INTO tmp_end_date SELECT ID, tgs_rec_eff_dtFROM (VALUES(1300505,'2012-08-01 15:57:15'),(1300505,'2012-08-01 15:55:16'), (1300505,'2012-07-30 11:29:34'),(1300505,'1905-07-01'))a(ID, tgs_rec_eff_dt);
SELECT a.ID, a.tgs_rec_eff_dt AS startDate, b.tgs_rec_eff_dt AS endDateFROM tmp_end_date aOUTER APPLY (SELECT TOP 1 tgs_rec_eff_dt FROM tmp_end_date b WHERE a.tgs_rec_eff_dt < tgs_rec_eff_dt ORDER BY tgs_rec_eff_dt ASC) b;
ID startDate endDate----------- ----------------------- -----------------------1300505 2012-08-01 15:57:15.000 NULL1300505 2012-08-01 15:55:16.000 2012-08-01 15:57:15.0001300505 2012-07-30 11:29:34.000 2012-08-01 15:55:16.0001300505 1905-07-01 00:00:00.000 2012-07-30 11:29:34.000