Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Months between two dates

Tags:

sql

sql-server

Is it possible to get month names between two dates in SQl

ie, 2011-05-01 And 2011-08-01 are the inputs I just want the output as

------------ Month ------------ May June July August 

If any body knows the query please share.

like image 785
Nithesh Narayanan Avatar asked Oct 25 '11 07:10

Nithesh Narayanan


People also ask

How do I calculate months between two dates in Excel?

To find the number of months or days between two dates, type into a new cell: =DATEDIF(A1,B1,”M”) for months or =DATEDIF(A1,B1,”D”) for days.

How do you calculate 12 months from a date?

To get around this, bump the date by one in the end. For example, June 1, 2000 to June 1, 2001 is less than twelve months. However, June 1, 2000 to June 2, 2001 is 12 months.

How do I calculate months between two dates in Excel without Datedif?

The YEARFRAC function returns the year fraction representing the number of whole days between start_date and end_date. ⇒ Type =INT(YEARFRAC(C4,D4)*12) & press Enter. You'll see the same result as found before.


2 Answers

DECLARE @StartDate  DATETIME,         @EndDate    DATETIME;  SELECT   @StartDate = '20110501'                 ,@EndDate   = '20110801';   SELECT  DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate)) AS MonthName FROM    master.dbo.spt_values x WHERE   x.type = 'P'         AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate); 

Results:

MonthName ------------------------------ May June July August  (4 row(s) affected) 
like image 104
Bogdan Sahlean Avatar answered Sep 18 '22 12:09

Bogdan Sahlean


You can do this with a recursive CTE, by building up a table of dates, and getting the month name from each:

declare @start DATE = '2011-05-01' declare @end DATE = '2011-08-01'  ;with months (date) AS (     SELECT @start     UNION ALL     SELECT DATEADD(month,1,date)     from months     where DATEADD(month,1,date)<=@end ) select Datename(month,date) from months 
like image 44
Jamiec Avatar answered Sep 17 '22 12:09

Jamiec