CTE (共通テーブル式 ) は特殊な一時テーブルのように使用できます。これにより、(この場合) 後で自己結合を作成できる行番号を動的に作成できます。
このようなものを探していると思います:
--create temp table select 19 as id,'2013-08-23 14:52' as activitytime,1 as status into #temp union all select 19,'2013-08-23 14:50',1 union all select 19,'2013-08-23 14:45',2 union all select 19,'2013-08-23 14:35',2 union all select 19,'2013-08-23 14:32',1 union all select 19,'2013-08-23 14:30',1 union all select 19,'2013-08-23 14:25',2 union all select 19,'2013-08-23 14:22',2 union all select 53,'2013-08-23 14:59',1 union all select 53,'2013-08-23 14:56',1 union all select 53,'2013-08-23 14:57',1 union all select 53,'2013-08-23 14:52',2 union all select 53,'2013-08-23 14:50',2 union all select 53,'2013-08-23 14:49',2 union all select 53,'2013-08-23 14:18',2 union all select 53,'2013-08-23 14:30',1 --build cte table ;WITH cte AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY id, activitytime) AS RowNum FROM #temp ) --query cte table, self joining row 1 to row 2 to compare. SELECT a.id, sum(DATEDIFF(minute,b.ActivityTIme,a.ActivityTime)) as TotalTime FROM cte AS A LEFT OUTER JOIN cte AS B ON A.RowNum = B.RowNum + 1 and a.id = b.id where b.status = 2 group by a.id
プレ>