我希望找出是否有办法计算这周的日期范围。
例如
Monday - 2016-11-21
Tuesday - 2016-11-22
Wednesday - 2016-11-23
依此类推。
如果有人可以帮我解决那些很棒的语法和计算方法。
答案 0 :(得分:3)
如果您在自己的专栏中对他们感到满意,那么您可以做这样的事情;
SELECT
DATEADD(wk, DATEDIFF(wk, 6, GETDATE()), 0) Last_Monday
,DATEADD(WEEK, DATEDIFF(WEEK, 2, GETDATE()) - 1, 1) Last_Tuesday
,DATEADD(WEEK, DATEDIFF(WEEK, 2, GETDATE()) - 1, 2) Last_Wednesday
,DATEADD(WEEK, DATEDIFF(WEEK, 2, GETDATE()) - 1, 3) Last_Thursday
结果;
Last_Monday Last_Tuesday Last_Wednesday Last_Thursday
2016-11-14 00:00:00.000 2016-11-15 00:00:00.000 2016-11-16 00:00:00.000 2016-11-17 00:00:00.000
如果你需要行,那么只需结合结果;
SELECT DATEADD(wk, DATEDIFF(wk, 6, GETDATE()), 0) Date_Field, 'Last_Monday' Day_Name
UNION
SELECT DATEADD(WEEK, DATEDIFF(WEEK, 2, GETDATE()) - 1, 1), 'Last_Tuesday'
UNION
SELECT DATEADD(WEEK, DATEDIFF(WEEK, 2, GETDATE()) - 1, 2), 'Last_Wednesday'
UNION
SELECT DATEADD(WEEK, DATEDIFF(WEEK, 2, GETDATE()) - 1, 3), 'Last_Thursday'
结果;
Date_Field Day_Name
2016-11-14 00:00:00.000 Last_Monday
2016-11-15 00:00:00.000 Last_Tuesday
2016-11-16 00:00:00.000 Last_Wednesday
2016-11-17 00:00:00.000 Last_Thursday
请阅读此处以获得有关其工作原理的详细说明;
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) Can someone explain me this
答案 1 :(得分:0)
DECLARE @StartDT DATE = '2016-11-21'
;WITH CTE (_Date)
AS (
SELECT @StartDT
UNION ALL
SELECT DATEADD(DAY, 1, _Date)
FROM CTE
WHERE _Date < DATEADD(DAY, 6, @StartDT)
)
SELECT _Date
,DATENAME(W, _Date)
FROM CTE
答案 2 :(得分:0)
您可以设置一周的开始和结束日期,并通过这些日期进行迭代:
Declare @startDay datetime,
@endDay datetime,
@iterDate datetime
Set @startDay = dateadd(day, datediff(day, 0, getdate()) / 7 * 7, 0) --Starting day of this week
Set @endDay = dateadd(day, 7, @startDay)
Set @iterDate = @startDay
Declare @tmpResults Table (Date datetime, DayName varchar(20))
While (@iterDate < @endDay)
Begin
Insert into @tmpResults (Date, DayName)
Values (@iterDate, datename(weekday, @iterDate))
Set @iterDate = dateadd(day, 1, @iterDate)
End
select Date, DayName From @tmpResults
结果: