EN VI

Sql-server - How do I list the months for the last 10 years starting from the current month in SQL Server?

2024-03-13 20:30:04
Sql-server - How do I list the months for the last 10 years starting from the current month in SQL Server

How do I list the months for the last 10 years starting from the current month using SELECT statement?

I can list all the current months since the last 10 years but could not list all the 12 subsequent months in the years

select top 10 dateadd(year, -1*row_number() over (order by name)+1, convert (varchar, getdate(),112)) as y
from sys.objects

will give me the last 10 years from the current month

202403...201503

select top 12 dateadd(MM, -1*row_number() over (order by name)+1, convert (varchar, getdate(),112)) as m
from sys.objects

will give me the last 12 month from today

But how do I merge the 2 statements above to get all the months from the last 10 years from the current month?

Please advise.

Solution:

Just one option using a ad-hoc tally/numbers table

Select N
      ,YrMth = format(dateadd(month,-N,getdate()),'yyyyMM')
 From  (
        Select Top (121) N=-1+Row_Number() Over (Order By (Select NULL)) 
         From  sys.objects
      ) B

Results

N   YrMth
0   202403
1   202402
2   202401
3   202312
4   202311
5   202310
6   202309
...
118 201405
119 201404
120 201403
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login