t-sql select get all Months within a range of years

前端 未结 8 572
悲哀的现实
悲哀的现实 2020-12-18 05:06

I need a select to return Month and year Within a specified date range where I would input the start year and month and the select would return month and year from the date

8条回答
  •  独厮守ぢ
    2020-12-18 05:57

    ---Here is a version that gets the month end dates typically used for accounting purposes

    DECLARE @StartDate datetime;
     DECLARE @EndDate datetime; 
     SET @StartDate = '2010-1-1'; 
     SET @EndDate = '2020-12-31';  
     --Procedure here:   
    
    
    
    
    
     WITH RecursiveRowGenerator (Row#, Iteration)                             
     AS (        SELECT 1, 1         
     UNION ALL        
     SELECT Row# + Iteration, Iteration * 2         
      FROM RecursiveRowGenerator         
      WHERE Iteration * 2 < CEILING(SQRT(DATEDIFF(MONTH, @StartDate, @EndDate)+1)) 
      UNION ALL        SELECT Row# + (Iteration * 2), Iteration * 2 
               FROM RecursiveRowGenerator         
               WHERE Iteration * 2 < CEILING(SQRT(DATEDIFF(MONTH, @StartDate, @EndDate)+1))      )  
                   , SqrtNRows AS (        SELECT *          FROM RecursiveRowGenerator         
     UNION ALL        SELECT 0, 0      ) 
     SELECT TOP(DATEDIFF(MONTH, @StartDate, @EndDate)+1)         
               DateAdd(d,-1,DateAdd(m,1, DATEADD(month, DATEDIFF(month, 0, @StartDate) + A.Row# * POWER(2,CEILING(LOG(SQRT(DATEDIFF(MONTH, @StartDate, @EndDate)+1))/LOG(2))) + B.Row#, 0)  ))
    Row#   FROM SqrtNRows A, SqrtNRows B  ORDER BY A.Row#, B.Row#; 
    

提交回复
热议问题