0

I wanted to get the week from the given date, for this I tried with the DATENAME function to get the WEEK like,

 Select DateName(WEEK,'2012-03-09')

am getting the output as 10. I want to get the starting date and ending date of this week like, 2012-03-04 to 2012-03-10 Is it possible?

4

3 に答える 3

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));
于 2012-04-12T13:34:23.227 に答える
1

以下を試して、getdateをあなたの日付に変更してください

Select 
DateAdd(d, 1- DatePart(dw,GetDate()),GetDate()) FirstDayOfWeek,
DateAdd(d, 7- DatePart(dw,GetDate()),GetDate()) LastDayOfWeek
于 2012-04-12T13:35:41.727 に答える
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
于 2012-04-13T12:53:36.107 に答える