Friday, March 1, 2013

[SQL Server] Using an amemded @From and @To date to get a new result

[SQL Server] Using an amemded @From and @To date to get a new result


Using an amemded @From and @To date to get a new result

Posted: 28 Feb 2013 08:40 PM PST

This is my criteria for the SQL below:From Date 07 Jan 2013 To Date 18 Mar 20131 - 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 = 10So 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 DatetimeDeclare @To DatetimeSet @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)

No comments:

Post a Comment

Search This Blog