Calculate time duration

Lylyy 380 Reputation points
2023-09-29T09:31:01.69+00:00

I have a table with status_id and time column. Need to calculate time duration of status=1.

Sample data like this:

CREATE TABLE #Temp (Id int, status_id int, [Time] DateTime);
INSERT INTO #Temp  VALUES
(1, 0, '2023-10-13 05:23:19.433'),
(1, 1, '2023-10-13 08:32:45.230'),
(1, 0, '2023-10-13 10:04:29.470'),
(1, 0, '2023-10-13 10:53:54.527'), 
(2, 1, '2023-10-13 11:32:39.213'), 
(2, 1, '2023-10-13 12:14:10.837'), 
(2, 0, '2023-10-13 16:02:10.117'), 
(2, 0, '2023-10-13 17:55:10.380')

For example, the duration of these two records is 92 minutes.

(1, 1, '2023-10-13 08:32:45.230'),

(1, 0, '2023-10-13 10:04:29.470'),

The final result should be:

id sum_diff

1 92

2 270

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,993 questions
0 comments No comments
{count} votes

Accepted answer
  1. LiHongMSFT-4306 27,961 Reputation points
    2023-09-29T09:42:46.4166667+00:00

    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

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.