CTE (ekspresi tabel umum ) dapat digunakan seperti tabel suhu khusus. Ini memungkinkan Anda untuk (dalam hal ini) secara dinamis membuat nomor baris yang nantinya dapat Anda buat sendiri bergabung.
Saya pikir Anda sedang mencari sesuatu seperti ini:
--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