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

前端 未结 8 573
悲哀的现实
悲哀的现实 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:54

    Code below generates the values for the range between 21 Jul 2013 and 15 Jan 2014. I usually use it in SSRS reports for generating lookup values for the Month parameter.

    declare
        @from date = '20130721',
        @to date = '20140115';
    
    with m as (
    select * from (values ('Jan', '01'), ('Feb', '02'),('Mar', '03'),('Apr', '04'),('May', '05'),('Jun', '06'),('Jul', '07'),('Aug', '08'),('Sep', '09'),('Oct', '10'),('Nov', '11'),('Dec', '12')) as t(v, c)),
    
    y as (select cast(YEAR(getdate()) as nvarchar(4)) [v] union all select cast(YEAR(getdate())-1 as nvarchar(4)))
    
    select m.v + ' ' + y.v [value_field], y.v + m.c [label_field]
    from m
    cross join y
    where y.v + m.c between left(convert(nvarchar, @from, 112),6) and left(convert(nvarchar, @to, 112),6)
    order by y.v + m.c desc
    

    Results:

    value_field     label_field
    ---------------------------
    Jan 2014        201401
    Dec 2013        201312
    Nov 2013        201311
    Oct 2013        201310
    Sep 2013        201309
    Aug 2013        201308
    Jul 2013        201307
    

提交回复
热议问题