简体   繁体   中英

How do I get the last 12 months date of today?

How can I get the last 12 months date as of today ?

Ex:

2020-10-21
2020-09-21
2020-08-21
2020-07-21
2020-06-21
2020-05-21
2020-04-21
2020-03-21
2020-02-21
2020-01-21

I tried this :

SELECT GETDATE() 'Today', 
           DATEADD(mm,-1,GETDATE())

But this gives me only last month.

If you want to generate those rows, you can use a recursive query:

with cte as (
    select 0 n
    union all select n + 1 from cte where n < 12
)
select dateadd(month, -n, convert(date, getdate())) dt from cte order by dt

This gives you today's date, and the same day of the month for the preceding 12 month (so that's a total of 13 rows). You can adjust the inequality condition in cte to the the exact number of iterations that you want. If you need more than 100 iterations, then you need to add option (maxrecursion 0) at the end of the query.

You could use a recursive CTE, but these can have rather negative impact on performance sometimes. If you don't have a numbers table that would be useful here, you can use a system table to generate rows and ROW_NUMBER() window function to give them numbers 1..12, like so:

select top 12 dateadd(month, 1-row_number() over (order by (select null)), getdate()) 
  from sys.all_objects

Working example on dbfiddle.uk, both recursive and with the above

Using an inline tally seems simple enough here, in my opinion:

SELECT DATEADD(MONTH,T.I,V.[Date])
FROM (VALUES(CONVERT(date,GETDATE())))V([Date])
     CROSS APPLY (VALUES(0),(-1),(-2),(-3),(-4),(-5),(-6),(-7),(-8),(-9),(-10),(-11))T(I);

There's various ways to generate a sequence of numbers between 1 and 12. Pick one. Once you have the sequence you just need to add DATEADD to it, eg like this:

SELECT DISTINCT
DATEADD(MONTH, 0-Number, GETDATE())
FROM master.dbo.spt_values
WHERE Number BETWEEN 1 AND 12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM