Try this approach and see if it is fast enough-- Prepare test datadeclare @messages table (mid int, username int, senddate datetime)set dateformat dmyinsert @messagesselect 1, 100, '16/07/06 13:00' union allselect 2, 100, '17/07/06 14:00' union allselect 3, 101, '17/07/06 14:30' union allselect 4, 102, '17/07/06 15:00' union allselect 5, 103, '18/07/06 16:00' union allselect 6, 100, '18/07/06 17:00' union allselect 7, 102, '18/07/06 18:01' union allselect 8, 103, '19/07/06 18:02' union allselect 9, 110, '19/07/06 19:03' union allselect 10, 102, '19/07/06 19:04' union allselect 11, 100, '21/07/06 20:00' union allselect 12, 103, '21/07/06 20:00' union allselect 13, 102, '21/07/06 20:00'-- Do the work (this is the code you run on your computer).select b0.i * isnull(min(m0.mid), 0) + b1.i * isnull(min(m1.mid), 0) + b2.i * isnull(min(m2.mid), 0) midsfrom ( select username, min(mid) mid from @messages group by username ) m0left join @messages m1 on m1.username = m0.username and m1.mid > m0.midleft join @messages m2 on m2.username = m1.username and m2.mid > m1.midcross join (select 0 i union all select 1) b0cross join (select 0 i union all select 1) b1cross join (select 0 i union all select 1) b2where b0.i + b1.i + b2.i = 1group by m0.username, b0.i, b1.i, b2.ihaving b0.i * isnull(min(m0.mid), 0) + b1.i * isnull(min(m1.mid), 0) + b2.i * isnull(min(m2.mid), 0) > 0order by m0.username, b0.i * isnull(min(m0.mid), 0) + b1.i * isnull(min(m1.mid), 0) + b2.i * isnull(min(m2.mid), 0)
Output isMids---- 1 2 6 3 4 7 10 5 8 12 9
Peter LarssonHelsingborg, Sweden