1

给定一个包含开始和结束日期以及它们正在发生的区域的项目表,我试图让我的结果输出在给定时间间隔内每周活动项目的数量并按地区分组。

我在项目中有很多看起来像的记录

地区 start_date end_date
阿拉巴马州 2012-07-08 2012-08-15
德州 2012-06-13 2012-07-24
阿拉巴马州 2012-07-25 2012-09-13
德州 2012-08-08 2012-10-28
佛罗里达州 2012-07-03 2012-08-07
路易斯安那州 2012-07-14 2012-08-12
……

如果我想要一周的结果,我可以做类似的事情

DECLARE @today datetime
SET @today ='2012-11-09'

SELECT 
[Region],
count(*) as ActiveProjectCount
FROM [MyDatabase].[dbo].[Projects]
where (datecompleted is null and datestart < @today) OR (datestart < @today AND @today     < datecompleted)
Group by region
order by region asc

这产生

区域 ActiveProjectCount
阿肯色州 15
路易斯安那州 18
北达科他州 18
俄克拉荷马州 27
...

如何更改此查询以生成看起来像的结果

地区 10/06 10/13 10/20 10/27    
阿肯色州 15 17 12 14
路易斯安那州 3 0 1 5
北达科他州 18 17 16 15
俄克拉荷马州 27 23 19 22
...

在每周的间隔中,我可以看到活动项目的总数(开始和结束日期之间的项目)

4

1 回答 1

4

你可以做某事。像这样:

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"
)
, "counted"
as
(
select
  "intervalId" = I."id"
  , I."startDate"
  , I."endDate"
  , D."region"
  , "activeProjects" = count(D."region") over ( partition by I."id", D."region" )

from
  "intervals" I
  inner join "data" D
    on D."startDate" <= I."startDate"
    and D."endDate" > I."endDate"
)

select
  *
from
(
  select
    "region"
    , "intervalId"
  from
    "counted"
) as Data
pivot
( count(Data."intervalId") for intervalId in ("25", "26", "27", "28", "29", "30", "31")) as p

可以根据需要定义间隔。

SQL-Fiddle

于 2012-11-16T23:12:40.540 回答