Another option. This returns for each account/Code even if it is the only code in the sequence:(it's kind of ugly though :)declare @t table (Account int, Code varchar(15), Dt datetime)insert @t select 123456, 'INBND', '10/15/2010 1:43:00 PM' union allselect 123456, 'CICBND', '10/15/2010 1:45:00 PM' union allselect 123456, 'CICBND', '10/15/2010 1:55:00 PM' union allselect 123456, 'CICBND', '10/16/2010 6:53:00 PM' union allselect 123456, 'OTBND', '10/17/2010 11:17:00 PM' union allselect 123456, 'CICBND', '10/22/2010 5:29:00 PM' union allselect 123456, 'OTBND', '10/25/2010 9:15:00 AM';with c1 as ( select account ,code ,dt ,row_number() over (partition by account order by dt) rn from @t ),c2 as ( select account ,code ,min(rn) rn from c1 group by account ,code ),c3 as ( select c1.account ,c2.code ,min(c1.rn) rn from c2 join c1 on c1.account = c2.account and c1.code != c2.code and c1.rn > c2.rn group by c1.account ,c2.code )select c1.account ,c1.code ,max(dt) datefrom c3join c1 on c1.account = c3.account and c1.code = c3.code and c1.rn < c3.rngroup by c1.account ,c1.codeOUTPUT:account code date----------- --------------- -----------------------123456 CICBND 2010-10-16 18:53:00.000123456 INBND 2010-10-15 13:43:00.000123456 OTBND 2010-10-17 23:17:00.000
Be One with the OptimizerTG