当GETDATE()作为输入时,是否可以获得一个月第一周的日期。
我可以通过以下代码获取当周的日期: -
select
convert(varchar(50), dateadd(dd, - datepart(dw, GETDATE()) + 1, GETDATE()), 101),
convert(varchar(50), dateadd(dd, - datepart(dw, GETDATE()) + 7, GETDATE()), 101)
如何根据GETDATE()
作为输入获取该月第一周,第二周的日期?
例如:
由于
编辑: - 我使用以下查询来获取给定月份的每周开始和结束日期: -
DECLARE @date date = '2016-07-08'--sample date
DECLARE @firstDay date = DATEADD(M, DATEDIFF(M, 0, @date), 0)
DECLARE @firstWeekLastDay date = DATEADD(D, 7-DATEPART(DW, @firstDay), @firstDay)
DECLARE @secondWeekFirstDay date = DATEADD(D, 2, @firstWeekLastDay)
DECLARE @secondWeekLastDay date = DATEADD(D, 5, @secondWeekFirstDay)
DECLARE @thirdWeekfirstDay date = DATEADD(D, 2, @secondWeekLastDay)
DECLARE @thirdWeekLastDay date = DATEADD(D, 5, @thirdWeekfirstDay)
DECLARE @fourthWeekFirstDay date = DATEADD(D, 2, @thirdWeekLastDay)
DECLARE @fourthWeekLastDay date = DATEADD(D, 5, @fourthWeekFirstDay)
DECLARE @fifthWeekFirstDay date = DATEADD(D, 2, @fourthWeekLastDay)
DECLARE @fifthWeekLastDay date = DATEADD(D, 5, @fifthWeekFirstDay)
SELECT @firstDay, @firstWeekLastDay, @secondWeekFirstDay, @secondWeekLastDay, @thirdWeekfirstDay, @thirdWeekLastDay, @fourthWeekFirstDay, @fourthWeekLastDay
答案 0 :(得分:1)
您可以使用以下查询获取范围:
(testEnv) Extra Drive 1 > echo $PATH
/media/suraj/Extra\ Drive\ 1/testEnv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/suraj/.config/composer/vendor/bin/:/usr/local/aws/bin
您还可以计算当月的第一个星期日:
DECLARE @date date = '2016-07-08'--sample date
DECLARE @firstDay date = DATEADD(M, DATEDIFF(M, 0, @date), 0)
SELECT CASE DATEPART(DW, @firstDay)
WHEN 1 THEN DATEADD(D, 1, @firstDay)
ELSE @firstDay END D1,
DATEADD(D, 7-DATEPART(DW, @firstDay), @firstDay) D2
第一周将从DECLARE @date date = '2016-08-01'
DECLARE @firstDayOfMonth date = DATEADD(M, DATEDIFF(M, 0, @date), 0)
DECLARE @firstSundayOfMonth date = DATEADD(D, (DATEDIFF(D, '2016-08-07', @firstDayOfMonth))/7*7, '2016-08-07')
到1
,第二周 - 从sunday-1
到sunday+1
。
答案 1 :(得分:0)
这将为您提供该月第1周和第2周的所有日期,除了基于GETDATE()的星期日。如果要测试特定日期,只需更改@date变量的值。
DECLARE @dt1 Datetime, @dt2 Datetime
DECLARE @date Datetime = GETDATE()
SELECT @dt1 = DATEADD(MM, DATEDIFF(MM, 0, @date), 0)
SELECT @dt2 = DATEADD(DD,14 , @dt1 )
;WITH daterange
AS
(
SELECT [dates]=@dt1 ,
DATEPART(WEEKDAY, @dt1) WD, --Weekday
DATEPART(DD,@dt1) [DAY], -- Day
1 WN -- Week no.
UNION ALL
SELECT [dates] + 1 ,
DATEPART(WEEKDAY, [dates] + 1) WD, --Weekday
DATEPART(DD,[dates] + 1) [DAY], --Day
CASE WHEN DATEPART(WEEKDAY, [dates] + 1) = 1 AND [DAY]<>1 THEN WN + 1 ELSE WN END WN --Week no.
FROM daterange
WHERE [dates] + 1<= @dt2
)
SELECT [dates]
FROM daterange C
WHERE WN <= 2 AND WD <> 1