Click here to Skip to main content
15,921,697 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello I wanted to get the list of last 5 month name from current date. AND Using the below sql query i am get it but here i wanted to get the list in between the specific date how to get the list of last 5 month between specific date.

What I have tried:

;with cte as
(select 0 as num
union all
select num+1 from cte where num<4)
select month(dates) as MonthID,datename(month,dates) as MonthName,year(dates) Year,datename(m,dates)+' '+cast(datepart(yyyy,dates) as varchar) as MonthYearName
from (select dateadd(mm,-num,DATEADD(dd,1,eomonth(getdate(),-1))) as dates from cte) A
Posted
Updated 30-May-18 2:29am

If I understand your question, correctly, see: SQL BETWEEN Operator[^]

If you need this to continue change with each day, also look at: SQL Server DATEADD() Function[^] and thus automatically select a rolling date range based upon the current date from getdate()
 
Share this answer
 
Instead of using numbers in your sequence cte and then doing a sub-query, just use dates. You can then have the start and end dates as variables. E.g. like this
SQL
declare @startdate date = '2018-FEB-01'
declare @enddate date = '2018-NOV-10'

;WITH cte AS
(
    SELECT  @startdate AS num
    UNION ALL
    SELECT  dateadd(mm, 1, num)
    FROM    cte
    WHERE dateadd(mm, 1, num) < @enddate
)
SELECT  month(num) as MonthID, 
        datename(month, num) as MonthName, 
        year(num) as [Year], 
        datename(m,num)+' '+cast(datepart(yyyy,num) as varchar) as MonthYearName
FROM    cte 
order by month(num) desc
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900