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