Reputation: 157
Could someone advise how I can go about counting the number of first day of month between two dates?
For example: 02/01/2015
to 05/05/2015
will count as 4
.
Upvotes: 1
Views: 825
Reputation: 35780
It can be accomplished easily like this:
DECLARE @sd DATE = '02/02/2015', @ed DATE = '05/01/2015'
SELECT DATEDIFF(mm, @sd, @ed) + CASE WHEN DAY(@sd) = 1 THEN 1 ELSE 0 END
Upvotes: 5
Reputation: 44881
If you have a sequence of dates stored somewhere (like in a calendar table) you can easily count the dates matching the day(date)
predicate. If you don't have any suitable table with a date sequence you can use a recursive common table expression to generate one on the fly like this:
declare @start date
set @start = '02/01/2015'
declare @end date
set @end = '05/05/2015'
;with dates (date) as (
select @start date
union all
select dateadd(day, 1, date) as date from dates where date < @end
)
select count(*) no_of_firsts from dates where day(date) = 1
Upvotes: 3