Q:

How to return values from SQL server database within intervals

Hi I have an SQL server database with 3 columns Activity[start_date(datetime),end_date(datetime),title(string)]
 and I wish to count for a whole year, how many activities have start_date in each month, I mean I would like a return of 12 values(12 months) that count the activities within the months, thanks.

A:

If there is an index on start_date and/or if you need to include months in the result even if there was no activity in that month, you might consider this one:
DECLARE @year INT;
SET @year = 2012;

;WITH n AS 
(
  SELECT TOP (12) m = DATEADD(MONTH, ROW_NUMBER() OVER 
    (ORDER BY name)-1, DATEADD(YEAR, @year-1900, 0))
    FROM sys.all_objects ORDER BY name
)
SELECT [Month] = n.m, ActivityCount = COUNT(t.title) 
FROM n 
LEFT OUTER JOIN dbo.unspecified_table_name AS t
  ON t.start_date >= n.m
  AND t.start_date < DATEADD(MONTH, 1, n.m)
GROUP BY n.m
ORDER BY [Month];

(If you don't want a row when there were zero activities in a given month, then change LEFT OUTER to INNER.)

