sql >> Base de Datos >  >> RDS >> Sqlserver

Obtener diferencia horaria entre grupos de registros

CTE (expresiones de tabla comunes ) se puede utilizar como una tabla temporal especializada. Le permite (en este caso) crear dinámicamente un número de fila en el que luego puede crear una autounión.

Creo que estás buscando algo como esto:

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