我会用这个:
SELECT Closing_Date = DATEADD(MONTH, DATEDIFF(MONTH, 0, Closing_Date), 0),
Category,
COUNT(Status) TotalCount
FROM MyTable
WHERE Closing_Date >= '2012-02-01'
AND Closing_Date <= '2012-12-31'
AND Defect_Status1 IS NOT NULL
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Closing_Date), 0), Category;
这将在每个月的第一天分组
`DATEADD(MONTH, DATEDIFF(MONTH, 0, '20130128'), 0)`
会给'20130101'
。我通常更喜欢这种方法,因为它将日期保留为日期。
或者,您可以使用如下所示的内容:
SELECT Closing_Year = DATEPART(YEAR, Closing_Date),
Closing_Month = DATEPART(MONTH, Closing_Date),
Category,
COUNT(Status) TotalCount
FROM MyTable
WHERE Closing_Date >= '2012-02-01'
AND Closing_Date <= '2012-12-31'
AND Defect_Status1 IS NOT NULL
GROUP BY DATEPART(YEAR, Closing_Date), DATEPART(MONTH, Closing_Date), Category;
这实际上取决于您所需的输出是什么。(在您的示例中,不需要关闭年份,但是如果日期范围超出了年份范围,则可能会是)。