TSQL script based on the below input

Vivaan Shresth 101 Reputation points
2022-03-28T18:30:49.333+00:00

Hi Team,

I have the below input:
187536-image.png

Output should be base on the above table:
187537-image.png
187635-image.png

Developer technologies Transact-SQL
{count} votes

Accepted answer
  1. Naomi Nosonovsky 8,431 Reputation points
    2022-03-28T19:47:04.293+00:00

    Try:

    ;WITH Groups AS (SELECT
         *,
         ROW_NUMBER() OVER (PARTITION BY BI, t.MEMBER_ID,ID ORDER BY StartDate,EndDate) AS RN,
    
        LAG(EndDate,1) OVER (PARTITION BY BI, t.MEMBER_ID,ID ORDER BY StartDate, EndDate) AS PreviousEndDate
    FROM @test t)
    
    SELECT BI, x.MEMBER_ID, ID, MIN(StartDate) AS StartDate, MAX(EndDate) AS EndDate
    
    FROM (SELECT
        *,
        CASE WHEN Groups.PreviousEndDate = DATEADD(DAY,-1,StartDate) THEN 0 ELSE 1 END AS IslandStartInd,
        SUM(CASE WHEN Groups.PreviousEndDate =DATEADD(DAY,-1,StartDate) THEN 0 ELSE 1 END) OVER (ORDER BY Groups.RN) AS IslandId
    FROM groups) x
    GROUP BY BI, X.MEMBER_ID, ID, x.IslandId
    

2 additional answers

Sort by: Most helpful
  1. Vivaan Shresth 101 Reputation points
    2022-03-28T18:33:19.967+00:00

    Please help me on tsql code and the results should be like below:
    187622-image.png

    0 comments No comments

  2. Naomi Nosonovsky 8,431 Reputation points
    2022-03-28T18:58:43.097+00:00

    This should help you to solve the problem - if you want tested solution, please post DDL (using table variable) and script to create data:

    https://www.mssqltips.com/sqlservertutorial/9130/sql-server-window-functions-gaps-and-islands-problem/


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.