我想從給定日期獲得的一週,爲了這個,我用DATENAME函數試圖讓週一樣,在SQL DATENAME函數
Select DateName(WEEK,'2012-03-09')
正在逐漸爲10.我想要得到的輸出本週的開始日期和結束日期,2012-03-04 to 2012-03-10
可能嗎?
我想從給定日期獲得的一週,爲了這個,我用DATENAME函數試圖讓週一樣,在SQL DATENAME函數
Select DateName(WEEK,'2012-03-09')
正在逐漸爲10.我想要得到的輸出本週的開始日期和結束日期,2012-03-04 to 2012-03-10
可能嗎?
做這樣的事情:
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));
這不依賴於你的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
您正在使用哪個數據庫服務器? – Vikram 2012-04-12 13:30:49
sql 2008 ....... – shanish 2012-04-12 13:32:52
是否可以在「2012-03-04至2012-03-10」 – shanish 2012-04-12 13:51:21