Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Ottieni Differenza di tempo tra gruppi di record

CTE (espressioni di tabella comuni ) può essere utilizzato come una tabella temporanea specializzata. Ti consente (in questo caso) di creare dinamicamente un numero di riga su cui puoi creare in seguito un accesso automatico.

Penso che tu stia cercando qualcosa del genere:

--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