我想从给定的日期开始一周,为此我尝试使用DATENAME函数来获得WEEK,
Select DateName(WEEK,'2012-03-09')
我得到输出为10.我想得到本周的开始日期和结束日期,2012-03-04 to 2012-03-10
是否可能?
答案 0 :(得分:1)
做这样的事情:
DECLARE @MyDate Date = '2012-03-09';
-- This gets you the SUNDAY of the week your date falls in...
SELECT DATEADD(DAY, -(DATEPART(WEEKDAY, @MyDate) - 1), @MyDate);
-- This gets you the SATURDAY of the week your date falls in...
SELECT DATEADD(DAY, (7 - DATEPART(WEEKDAY, @MyDate)), @MyDate);
-- This will show the range as a single column
SELECT
CONVERT(NVarChar, DATEADD(DAY, -(DATEPART(WEEKDAY, @MyDate) - 1), @MyDate))
+ ' through ' +
CONVERT(NVarChar, DATEADD(DAY, (7 - DATEPART(WEEKDAY, @MyDate)), @MyDate));
答案 1 :(得分:1)
尝试以下操作,将getdate更改为您的日期
Select
DateAdd(d, 1- DatePart(dw,GetDate()),GetDate()) FirstDayOfWeek,
DateAdd(d, 7- DatePart(dw,GetDate()),GetDate()) LastDayOfWeek
答案 2 :(得分:0)
这不依赖于datefirst的默认设置。
set datefirst 4 -- this row does nothing in this query.
-- It will hurt the queries using datepart though
declare @t table(dt datetime)
insert @t values('2012-03-09 11:12'), ('2012-03-10 11:12'),('2012-03-11 11:12')
-- week from sunday to saturday
Select dateadd(week, datediff(week, 0, dt),-1),
dateadd(week, datediff(week, 0, dt),+5)
from @t