假设您想要一个特定的年份:
DECLARE @year INT;
SET @year = 2012;
DECLARE @start SMALLDATETIME;
SET @start = DATEADD(YEAR, @year-1900, 0);
;WITH y AS (SELECT TOP (12) rn = ROW_NUMBER() OVER (ORDER BY [object_id])-1
FROM sys.all_objects ORDER BY [object_id])
SELECT DATEADD(MONTH, y.rn, @start), COUNT(t.issueDate)
FROM y
LEFT OUTER JOIN dbo.MyTable AS t
ON t.issueDate >= DATEADD(MONTH, y.rn, @start)
AND t.issueDate < DATEADD(MONTH, y.rn + 1, @start)
GROUP BY DATEADD(MONTH, y.rn, @start);
如果它不是特定年份,那么您可以稍微不同地覆盖任何日期范围,只要您提供第一个月的第一天和上个月的第一天(或传递 4 个整数并手动构建日期):
DECLARE @startdate SMALLDATETIME, @enddate SMALLDATETIME;
SELECT @startdate = '20111201', @enddate = '20120201';
;WITH y AS (SELECT TOP (DATEDIFF(MONTH, @startdate, @enddate)+1)
rn = ROW_NUMBER() OVER (ORDER BY [object_id])-1
FROM sys.all_objects ORDER BY [object_id]
)
SELECT DATEADD(MONTH, y.rn, @startdate), COUNT(t.issueDate)
FROM y
LEFT OUTER JOIN dbo.MyTable AS t
ON t.issueDate >= DATEADD(MONTH, y.rn, @startdate)
AND t.issueDate < DATEADD(MONTH, y.rn + 1, @startdate)
GROUP BY DATEADD(MONTH, y.rn, @startdate);