Counts Days Per Month and Per Year b/w Two Dates

In  this blog we will learn how to retrieve number of days per month and per year b/w two dates.
 
Code: 

  1. DECLARE @start DATETIME, @end DATETIME;  
  2.   
  3. SELECT @start = '28-Oct-2015', @end = '05-May-2016';  
  4.   
  5. select year(dt) [Year], Month(dt) [Month], count(*) [Numer_Of_Days]  
  6.   
  7. from (select top(datediff(d, DATEADD(Day,-1, @start), @end)) dateadd(d, row_number() over (order by (select null)), DATEADD(Day,-1, @start)) dt  
  8.   
  9. from sys.columns) q  
  10.   
  11. group by year(dt), Month(dt)  
  12.   
  13. order by [Year]  
Result:

 
Ebook Download
View all
SQL Jobs
Read by 0 people
Download Now!
Learn
View all