-- 1 find the first nth weekday (Mon/Tue/Wed/Thu/Fri/Sat/Sun) of the month where @dt is in
-- for example, find the 5th Friday of the month of Aug, 2013
declare @nth int=5, @dt datetime='2013-08-12';
declare @dw tinyint =5 -- 1=Mon,2= Tue,3=Wed, 4=Thur, 5=Fri, 6=Sat, 7=Sun
select [1st_nth_wkday]=case when datepart(dw, dateadd(month,
datediff(month,0,@dt),0)[email protected]@datefirst-1) >= @dw
then dateadd(day, (@nth-1)*7 + (7-(datepart(dw, dateadd(month,
datediff(month,0,@dt),0)[email protected]@datefirst-1)[email protected])), dateadd(month,
datediff(month,0,@dt),0))
else dateadd(day, (@nth-1)*7 + (0-(datepart(dw, dateadd(month,
datediff(month,0,@dt),0)[email protected]@datefirst-1)[email protected])), dateadd(month,
datediff(month,0,@dt),0))
end
go
-- 2 find the last nth weekday (Mon/Tue/Wed/Thu/Fri/Sat/Sun) of the month
where @dt is in
-- find the 2nd last Sunday of current month
declare @nth int=2, @dt datetime=current_timestamp;
declare @dw tinyint =7 -- 1=Mon,2= Tue,3=Wed, 4=Thur, 5=Fri, 6=Sat, 7=Sun
select [last_nth_wkday]=case when datepart(dw, dateadd(month,
datediff(month,0,@dt)+1,0)[email protected]@datefirst-1) >= @dw
then dateadd(day, -(@nth-1)*7 - (datepart(dw, dateadd(month,
datediff(month,0,@dt)+1,0)[email protected]@datefirst-1)[email protected]), dateadd(month,
datediff(month,0,@dt)+1,0)-1)
else dateadd(day, -(@nth)*7 - (datepart(dw, dateadd(month,
datediff(month,0,@dt)+1,0)[email protected]@datefirst-1)[email protected]), dateadd(monI th,
datediff(month,0,@dt)+1,0)-1)
end
go
月份其實我這個博客在這裏的第三個星期五:http://www.sqlservercentral.com/blogs/jeffrey_yao/2014/03/02/fun-in-datetime-calculations/
那你試試這麼遠嗎? (WEEK,DATEDIFF(WEEK,0,DATEADD(DAY,6 - DATEPART(DAY,GETDATE()),GETDATE())),6)\t我使用過,請使用代碼 – Paolo 2014-10-08 07:49:32
@Paolo謝謝您的快速響應。這個查詢它將返回一個月的第一個星期日..但是dnt知道如何找到月的第n天..我需要根據用戶的請求返回第n天 – user3132347 2014-10-08 08:08:05