Hi @Lylyy
Try this query:
;WITH CTE AS
(
SELECT *,LAG(status_id) OVER(PARTITION BY id ORDER BY [time]) Lag_status,
LAG(time)OVER(PARTITION BY id ORDER BY [time]) Lag_time
FROM #Temp
)
SELECT Id, SUM(DATEDIFF(minute, Lag_time, [time])) sum_diff
FROM CTE
WHERE (status_id = 0 and Lag_status = 1)OR(status_id = 1 and Lag_status = 1)
GROUP BY Id
Best regards,
Cosmog Hong