I would use this:
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;
This will be grouped by the first of each month, therefore
`DATEADD(MONTH, DATEDIFF(MONTH, 0, '20130128'), 0)`
will give '20130101' . I usually prefer this method as it saves dates as dates.
Alternatively, you can use something like this:
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;
It really depends on your desired result. (The closing year is not needed in your example, but if the date range crosses the year, it could be).
GarethD Jan 28 '13 at 16:01 2013-01-28 16:01
source share