最近12个月

 declare @i int 
         declare @adjoinmontemp int
         declare @adjoinyear int
         IF OBJECT_ID('tempdb..#AdjoinMons') is not null
            drop table    #AdjoinMons

            create table #AdjoinMons (id int,adjoinyear int, adjoinmon int ,yearmon varchar(20) ) 

                set @i=1
                declare @date date
                set @date=convert(date, GETDATE()-1)
                while @i<13
                    begin
                    set  @adjoinyear =year( DATEADD(month,-@i,@date))
                    set  @adjoinmontemp=  MONTH( DATEADD(month,-@i,@date))
                      insert into #AdjoinMons (id,adjoinyear,adjoinmon,yearmon) values(@i,@adjoinyear,@adjoinmontemp, concat( @adjoinyear , '-'+RIGHT(concat( '0', @adjoinmontemp),2))  )
             
                   set @i=@i+1
                end
            select     *from  #AdjoinMons order by yearmon 

         drop table #AdjoinMons

 

posted @ 2017-09-29 16:43  纵一苇之所如-  阅读(105)  评论(0)    收藏  举报