Grouping in the sequence as it appears with timestamp

John D 20 Reputation points
2023-01-11T21:16:56.58+00:00

The table has binary value Auth and NonAuth in a a sequence - I would like to see start and end time of each Auth and NonAuth conditions:

Sample i/p

User's image

Expected o/p

User's image

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

Accepted answer
  1. Jingyang Li 5,891 Reputation points
    2023-01-11T22:51:29.31+00:00
    create table test (dt datetime, status varchar(20))
    
    insert into test (dt, status) 
    values
    ('2023-01-11 12:41','Auth'),
    ('2023-01-11 12:42','Auth'),
    ('2023-01-11 12:43','Auth'),
    ('2023-01-11 12:44','Auth'),
    ('2023-01-11 12:45','Auth'),
    ('2023-01-11 12:46','NonAuth'),
    ('2023-01-11 12:47','NonAuth'),
    ('2023-01-11 12:48','NonAuth'),
    ('2023-01-11 12:49','Auth'),
    ('2023-01-11 12:50','Auth')
    
    Select status,min(dt) as start_time, MAX(dt) as end_time
    from (
    Select status, dt 
    ,row_number() over(Order by dt)-row_number() over(partition by status Order by dt) as grp
    
    from test) t
    
    Group by status, grp
    order by min(dt)
    
    
    drop table test
    
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. LiHongMSFT-4306 29,746 Reputation points
    2023-01-12T02:51:03.9933333+00:00

    Hi @John D

    This is a typical Gaps and Islands Problem; you can refer to the following two articles for more details and learning.

    Introduction to Gaps and Islands Analysis

    SQL Server Window Functions Gaps and Islands Problem

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

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.