Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Calculating the number of Whole/Complete Months between two dates

$
0
0

It sounds easy but all the examples I have found so far have got this wrong.

I'm trying to use SQL to calculate the number of months between two dates, but these months must be complete months, partial months do not count and need to be ignored. All the examples found so far get this wrong. I've been playing the the following examples:

declare @start_date smalldatetimedeclare @end_date smalldatetimeset @start_date = '10-jan-2011'set @end_date = '15-feb-2011'selectDateDiff(Month, @start_date, @end_date + 1)selectDATEDIFF( m, @start_date, @end_date ) - CASEWHENDAY(@start_date) > DAY(@end_date) THEN 1 ELSE 0 END

Between the 10-Jan and 15-Feb the answer is zero, 15-Jan and 10-Feb the answer is still zero.

Between the 01-Jan and 28-Feb it should be 2.

Can I calculate this in a single TSQL statement?

Cheers

Steve


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>