-1

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)
4

3 回答 3

0
Declare @From Datetime
Declare @To Datetime

Set @From = '01 Mar 2013'
Set @To = '31 Mar 2013'


SELECT Datediff(Week, dateadd(dd, CASE WHEN datepart(weekday, @From) = 1 THEN 0 ELSE 8 - datepart(weekday, @From) END,@From), 
dateadd(dd, CASE WHEN datepart(weekday, @To) = 1 THEN 0 ELSE 1 - datepart(weekday, @To) END,@To))+1
于 2013-03-01T13:17:48.730 回答
0

我希望它有帮助:

Declare @From  Datetime 
Declare @To  Datetime 
Declare @temp  Datetime 
Declare @firstSunday DateTime
Declare @lastSunday DateTime

Set @From = '7 Jan 2013' 
Set @To = '18 Mar 2013'


set @temp = @From
WHILE ( @temp <= @To )
    BEGIN 
        IF DATEPART(dw, @temp) = 1
        BEGIN
            SET @firstSunday = @temp
            BREAK
        END

        set @temp = dateadd(dd,1,@temp)

    END


set @temp = @To
WHILE ( @temp >= @From )
    BEGIN

    IF DATEPART(dw, @temp) = 1
        BEGIN
            SET @lastSunday = @temp
            BREAK
        END

        set @temp = dateadd(dd,-1,@temp)

    END

SELECT @firstSunday, @lastSunday, DATEDIFF(dd,@firstSunday, @lastSunday)/7 +1
于 2013-03-01T10:57:51.277 回答
0

我认为这比我以前的答案更优雅但可读性更低

小提琴演示在这里

declare @From date = '20130107' --'7 Jan 2013' 
declare @To date = '20130318'  --'18 Mar 2013' 

select datediff(day,dateadd(day,wkdays,@from),@to)/7 + 
       case when wkdays = 0 and 
        datename(weekday,dateadd(day,wkdays,@from)) <> 'sunday' then 0 else 1 end 
from (values (0),(1),(2),(3),(4),(5),(6)) t(wkdays)
where dateadd(day,wkdays,@from) between @from and @to
      and datename(weekday,dateadd(day,wkdays,@from)) = 'sunday'
于 2013-03-01T13:42:47.163 回答