Here's one way: (which assumes your table order is determined by the dates in the table.--Your Table with your Sample datadeclare @t table (MEMBID int, DATEFROM datetime, DATETO datetime, duration int null)insert @t (membid, datefrom, dateto)select 06000031, '05/04/2007', '05/09/2007' union allselect 06000031, '05/30/2007', '06/04/2007' union all select 06000031, '07/22/2009', '07/24/2009' union allselect 06000031, '04/09/2010', '04/11/2010' union allselect 06000031, '05/28/2010', '05/30/2010' union allselect 06000145, '06/09/2007', '06/21/2007' union allselect 06000145, '06/27/2007', '07/20/2007' union allselect 06000145, '08/07/2007', '09/06/2007' union allselect 06000145, '09/29/2007', '10/05/2007' union allselect 06000145, '10/23/2007', '10/30/2007' union allselect 06000145, '10/30/2007', '11/02/2007' union allselect 06000145, '05/28/2008', '05/30/2008' union allselect 06000145, '08/09/2009', '08/18/2009' --One possible solution;with yak (membid, datefrom, dateto, seq)as( select membid ,datefrom ,dateto ,row_number() over (partition by membid order by datefrom) from @t)select a.membid ,a.datefrom ,a.dateto ,datediff(day, b.dateto, a.datefrom) durationfrom yak aleft outer join yak b on b.membid = a.membid and b.seq + 1 = a.seqorder by a.membid ,a.seqOUTPUT:membid datefrom dateto duration----------- ----------------------- ----------------------- -----------6000031 2007-05-04 00:00:00.000 2007-05-09 00:00:00.000 NULL6000031 2007-05-30 00:00:00.000 2007-06-04 00:00:00.000 216000031 2009-07-22 00:00:00.000 2009-07-24 00:00:00.000 7796000031 2010-04-09 00:00:00.000 2010-04-11 00:00:00.000 2596000031 2010-05-28 00:00:00.000 2010-05-30 00:00:00.000 476000145 2007-06-09 00:00:00.000 2007-06-21 00:00:00.000 NULL6000145 2007-06-27 00:00:00.000 2007-07-20 00:00:00.000 66000145 2007-08-07 00:00:00.000 2007-09-06 00:00:00.000 186000145 2007-09-29 00:00:00.000 2007-10-05 00:00:00.000 236000145 2007-10-23 00:00:00.000 2007-10-30 00:00:00.000 186000145 2007-10-30 00:00:00.000 2007-11-02 00:00:00.000 06000145 2008-05-28 00:00:00.000 2008-05-30 00:00:00.000 2086000145 2009-08-09 00:00:00.000 2009-08-18 00:00:00.000 436
Be One with the OptimizerTG