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

前端 未结 8 568
悲哀的现实
悲哀的现实 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 06:04

    you can do the following

    SELECT DISTINCT YEAR(myDate) as [Year], MONTH(myDate) as [Month]
    FROM myTable
    WHERE <<appropriate criteria>>
    ORDER BY [Year], [Month]
    
    0 讨论(0)
  • 2020-12-18 06:07

    You can use something like this: http://blogs.msdn.com/b/sqlazure/archive/2010/09/16/10063301.aspx

    To generate the equivalent of a numbers table using date ranges.

    But could you please clarify your inputs and outputs?

    Do you want to input a start date, for example, '2010-5-1' and end date, for example, '2010-8-1' and have it return every month between the two? Do you want to include the start month and end month, or exclude them?

    Here's some code that I wrote that will quickly generate an inclusive result of every month between two dates.

    --Inputs here:
    DECLARE @StartDate datetime;
    DECLARE @EndDate datetime;
    SET @StartDate = '2010-1-5 5:00PM';
    SET @EndDate = GETDATE();
    
    --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(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#;
    
    0 讨论(0)
提交回复
热议问题