Here's some sample data and the resultSample Datadeclare @t table ([user] varchar(1), imp_time datetime, imp_count int, click int, click_time datetime)insert @tselect 'a', '4/3/2010 9:48:03', 1, 0, NULLunion all select 'a', '4/8/2010 8:38:51', 2, 1, '4/8/2010 14:21:11'union all select 'a', '4/8/2010 14:21:05', 3, 1, '4/8/2010 14:21:11'union all select 'a', '4/8/2010 14:45:02', 4, 0, NULLunion all select 'a', '4/8/2010 20:18:05', 5, 0, NULLunion all select 'a', '4/10/2010 14:05:08', 6, 0, NULLunion all select 'b', '3/10/2010 12:45:19', 1, 1, '3/10/2010 15:10'union all select 'b', '3/10/2010 12:48:26', 2, 0, NULLunion all select 'b', '3/10/2010 12:50:39', 3, 1, '3/10/2010 15:10'union all select 'b', '3/10/2010 12:56:12', 4, 0, NULLunion all select 'b', '3/10/2010 14:18:08', 10, 1, '3/10/2010 15:10'
Queryselect a.*, case when b.imp_time is null then 0 else 1 end as final_click, b.imp_time as final_click_timefrom @t a left join(select [user], max(imp_time) as imp_timefrom @t where click = 1group by [user]) bon a.[user] = b.[user] and a.imp_time = b.imp_time
Resultuser imp_time imp_count click click_time final_click final_click_time---- ----------------------- ----------- ----------- ----------------------- ----------- -----------------------a 2010-04-03 09:48:03.000 1 0 NULL 0 NULLa 2010-04-08 08:38:51.000 2 1 2010-04-08 14:21:11.000 0 NULLa 2010-04-08 14:21:05.000 3 1 2010-04-08 14:21:11.000 1 2010-04-08 14:21:05.000a 2010-04-08 14:45:02.000 4 0 NULL 0 NULLa 2010-04-08 20:18:05.000 5 0 NULL 0 NULLa 2010-04-10 14:05:08.000 6 0 NULL 0 NULLb 2010-03-10 12:45:19.000 1 1 2010-03-10 15:10:00.000 0 NULLb 2010-03-10 12:48:26.000 2 0 NULL 0 NULLb 2010-03-10 12:50:39.000 3 1 2010-03-10 15:10:00.000 0 NULLb 2010-03-10 12:56:12.000 4 0 NULL 0 NULLb 2010-03-10 14:18:08.000 10 1 2010-03-10 15:10:00.000 1 2010-03-10 14:18:08.000