Derive multiple rows for month based on Start and end time

Prusty, Parthasarathi (Cognizant) 41 Reputation points
2023-06-19T16:21:25.74+00:00

I have a table where I have the start time and end time as given in below example.

DECLARE @TableTT AS TABLE
    (
  Id INT ,
  StartDate datetime ,
  EndDate datetime
)

INSERT  INTO @TableTT
    ( Id, StartDate, EndDate)
VALUES  ( 1, N'2023-01-19 15:23:09.960', '2023-05-14 15:23:09.960'),
    ( 2, N'2021-03-19 15:23:09.960', '2021-08-14 15:23:09.960')

User's image

I'll have only 3 columns ID, year and Month. I have to split the rows based on the Months. For exmple. I need output as below. Year would be derived from Startdate and Month will be calculated by subtracting startdate from enddate and that many rows for month should appear.

User's image

SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. Jingyang Li 5,896 Reputation points Volunteer Moderator
    2023-06-19T16:48:08.7833333+00:00
    DECLARE @TableTT AS TABLE
        (
      Id INT ,
      StartDate datetime ,
      EndDate datetime
    )
    
    INSERT  INTO @TableTT
        ( Id, StartDate, EndDate)
    VALUES  ( 1, N'2023-01-19 15:23:09.960', '2023-05-14 15:23:09.960'),
        ( 2, N'2021-03-19 15:23:09.960', '2021-08-14 15:23:09.960')
    
    
    	select Id,YEAR(StartDate),MONTH(StartDate)+n-1 
    	from @TableTT
    	cross apply (values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)) d(n)
    	where Eomonth(dateadd(month,n-1,StartDate))<=Eomonth(EndDate)
    

0 additional answers

Sort by: Most helpful

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.