Given a table of projects with start and end dates as well as a region that they are taking place, I am trying to get my result to output the number of active projects per week over a given interval and grouped by region.
I have many records in Projects that look like
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 ....
If I want results for a single week, I can do something like
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
This produces
Region ActiveProjectCount Arkansas 15 Louisiana 18 North Dakota 18 Oklahoma 27 ...
How can I alter this query to produce results that look like
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 ...
Where on a weekly interval, I am able to see the total number of active projects (projects between start and end date)
you could do sth. like this:
intervals can be defined as you wish.
see SQL-Fiddle