This is my criteria for the SQL below:
From Date 07 Jan 2013 To Date 18 Mar 2013
1 - First Sunday After 07 Jan 2013 is 13 Jan 2013 - Done (FirstSunday) 2 - First Sunday Before 18 Mar 2013 is 17 Mar 2013 - Done (LastSunday) 3 - How many days between 13 Jan 2013 and 17 Mar 2013 = 63, Divide 63 by 7 = 9, +1 = 10
So what I need my datediff to do is use the results from the 1st and 2nd rows above (First and Last Sundays date) so I get the correct result for section 3. Can you help?
Declare @From Datetime
Declare @To Datetime
Set @From = '07 Jan 2013'
Set @To = '18 Mar 2013'
Select dateadd(dd, CASE WHEN datepart(weekday, @From) = 1 THEN 0 ELSE 8 - datepart(weekday, @From) END,@From) as FirstSunday,
dateadd(dd, CASE WHEN datepart(weekday, @To) = 1 THEN 0 ELSE 1 - datepart(weekday, @To) END,@To) as LastSunday
,datediff(d,@From, @To)