这是我对以下SQL的标准:
自2013年1月7日至2013年3月18日
1 - 2013年1月7日后的第一个星期日是2013年1月13日 - 完成(FirstSunday) 2 - 第一个星期日2013年3月18日之前是2013年3月17日 - 完成(LastSunday) 3 - 2013年1月13日至2013年3月17日期间的天数= 63,除以63 = 7 = 9,+ 1 = 10
所以我需要我的约会做的是使用上面第1和第2行(第一个和上个星期日)的结果,所以我得到第3节的正确结果。你能帮忙吗?
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)
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
我认为这比my previous answer
更优雅但更少可读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'