-1
declare @startdate datetime='11/30/2012',@enddate datetime='12/6/2012'
Select 
Convert(varchar, DateAdd(dd, -(DatePart(dw, @startdate) - 1), @startdate), 101) As WeekStart,
Convert(varchar, DateAdd(dd, (7 - DatePart(dw, @enddate)), @enddate), 101) As WeekEnd

上面是代码,代码的输出是:

11/25 2012  12/08/2012

但我想在 2 周内分别显示结果。请问如何以这种格式显示数据?

11/25/2012  12/01/2012 ( 1 week)
12/02/2012  12/08/2012 ( 2 week)
4

1 回答 1

0

选中此项以设置一周的开始!下面的代码给出了预期的结果。SQL-Fiddle-Link 在底部。

declare @startdate  date = '2012-11-30';
declare @enddate    date = '2012-12-06';

with "nums"
as
(
  select 1 as "value"
  union all select "value" + 1 as "value"
  from "nums"
  where "value" <= 52
)
, "intervals"
as
(
  select
  "id" = "value"
  , "startDate" = cast( dateadd( week, "value" - 1, dateadd(year, datediff(year, 0, getdate()), 0)) as date )
  , "endDate" = cast( dateadd( week, "value", dateadd( year, datediff( year, 0, getdate()), 0 )) as date )

from
  "nums"
)
select
    "startDate", "endDate", row_number() over ( order by rand() ) as "number"
from
    "intervals"
where
    "startDate" <= @startdate and "endDate" > @startdate
    or
    "startDate" <= @enddate and "endDate" > @enddate

见 SQLFiddle

于 2012-12-19T00:35:45.340 回答