2012-11-16 53 views
1

給定一個包含開始日期和結束日期以及正在發生的區域的項目表,我試圖讓我的結果輸出活動項目的數量每週在給定的時間間隔內按地區分組。SQL獲取計數按星期和按給定日期間隔的類型分組

我有很多的記錄,看起來就像

 
region   start_date   end_date 
Alabama  2012-07-08   2012-08-15 
Texas   2012-06-13   2012-07-24 
Alabama  2012-07-25   2012-09-13 
Texas   2012-08-08   2012-10-28 
Florida  2012-07-03   2012-08-07 
Lousiana  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 

這將產生

 
Region   ActiveProjectCount 
Arkansas    15 
Louisiana    18 
North Dakota   18 
Oklahoma    27 
... 

項目如何更改此查詢以生成看起來像

 
Region   10/06 10/13 10/20 10/27  
Arkansas   15  17  12  14 
Louisiana   3  0  1  5 
North Dakota  18  17  16  15 
Oklahoma   27  23  19  22 
... 

凡在每週一次的間隔,我能看到活動項目(開始和結束日期之間的項目)

回答

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

相關問題