0

嗨,我有一个包含 3 列的 SQL 服务器数据库,Activity[start_date(datetime),end_date(datetime),title(string)] 我希望计算一整年,每个月有多少活动有 start_date,我的意思是我希望返回 12 个值(12 个月)来计算月份内的活动, 谢谢。

4

2 回答 2

0
select month(start_date) as Month, count(*) as Count
from Activity
where year(start_date) = 2011 
group by month(start_date)
order by month(start_date)
于 2012-07-12T19:29:00.957 回答
0

如果有一个索引start_date和/或如果您需要在结果中包含月份,即使该月份没有活动,您也可以考虑这个:

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];

(如果您不希望在给定月份的活动为零时出现一行,则更LEFT OUTER改为INNER。)

于 2012-07-12T19:39:41.007 回答