Here is one way (i think)set nocount oncreate table #scratch_table (identity_key int, sample_datetime datetime, stack_ID varchar(16))insert #scratch_tableselect 1, '2001-06-02 00:00:00.000', NULL union allselect 7, '2006-01-02 10:50:22.000', 'H505-2006-12-001' union allselect 8, '2006-01-02 10:50:25.000', 'H505-2006-12-003' union allselect 9, '2006-01-02 10:50:30.000', 'H505-2006-12-004' union allselect 10, '2006-03-02 10:50:30.000', 'H505-2006-12-004' union allselect 11, '2006-03-03 10:50:30.000', 'H505-2006-12-004' union allselect 16, '2006-03-04 13:21:58.000', 'H505-2006-12-001' union allselect 17, '2006-03-04 15:33:12.000', 'H505-2006-12-003' union allselect 18, '2006-03-04 15:34:15.000', 'H505-2006-12-003' union allselect 21, '2006-03-05 10:45:25.000', 'H505-2006-12-005' union allselect 38, '2006-03-06 11:05:25.000', 'H505-2006-12-007' union allselect 41, '2006-03-16 13:27:21.000', 'H505-2006-12-004' union allselect 42, '2006-03-16 13:27:21.500', 'H505-2006-12-004' union allselect 43, '2006-03-16 13:27:21.100', 'H505-2006-12-004'select interval_milliseconds = abs(datediff(millisecond, last, most_Recent)) ,[last] ,most_recentfrom ( select sample_datetime [last] ,most_recent = (select top 1 sample_datetime from #scratch_table where stack_id = a.stack_id order by sample_datetime desc) from #Scratch_table a where identity_key = (select max(identity_key) identity_key from #scratch_table) ) adrop table #scratch_tableoutput:interval_milliseconds last most_recent --------------------- ------------------------------------------------------ ------------------------400 2006-03-16 13:27:21.100 2006-03-16 13:27:21.500
Be One with the OptimizerTG