Can you please try the following? It uses DateDiff()
.
select datediff(day, startdate, enddate) as no_of_days,
month(fdate )as month
from leavedepot;
EDIT : SQLFIDDLE DEMO
Sample Data:
ID STARTDATE ENDDATE
1 2012-01-28 2012-02-02
2 2012-02-03 2012-02-10
Query:
SELECT month(startdate) as Month_Number,
datename(month, startdate) as Month, -- month is a reserved word
case when month(startdate) <> month(enddate)
then datediff(day, startdate, DATEADD(month,
((YEAR(startdate) - 1900) * 12)
+ MONTH(startdate), -1))
else datediff(day, startdate, enddate)
end
as Leaves
from myleaves
;
Results:
MONTH_NUMBER MONTH LEAVES
1 January 3
2 February 7
If you would want to exclude weekends by any chance...: Here we use a variable to define start end dates, but you can use your own table columns for it as well. :) Reference post: get DATEDIFF excluding weekends using sql server. You need to incorporate this query into the above.
declare @d1 datetime, @d2 datetime
select @d1 = '9/9/2011', @d2 = '9/18/2011'
select datediff(dd, @d1, @d2) - (datediff(wk, @d1, @d2) * 2) -
case when datepart(dw, @d1) = 1 then 1 else 0 end +
case when datepart(dw, @d2) = 1 then 1 else 0 end;
You may still remove your 2
days to exclude start and enddate...The functions we use datepart.