如何使用sql从date字段按月分组

我怎样才能从一个date字段按月分组(而不是按天)?

这是我的date字段的样子:

2012-05-01 

这是我目前的SQL:

 select 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 Closing_Date, Category 

我会用这个:

 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' 。 我通常更喜欢这种方法,因为它将date保留为date。

或者你可以使用这样的东西:

 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; 

这真的取决于你想要的输出是什么。 (在你的例子中,结束年份是不必要的,但是如果date范围跨过年份边界,则可能是)。

使用DATEPARTfunction从date中提取月份。

所以你会做这样的事情:

 SELECT DATEPART(month, Closing_Date) AS Closing_Month, COUNT(Status) AS TotalCount FROM t GROUP BY DATEPART(month, Closing_Date) 

我试过user1845584的解决scheme。 SQL给类别字段错误。 所以我删除它,它的工作。 另外我补充说:

 select Year(Closing_Date), Month(Closing_Date)" 

哪个更好 这意味着我已经按年份和月份列出了数量。

我使用FORMAT函数来完成这个工作:

 select FORMAT(Closing_Date, 'yyyy_MM') AS Closing_Month , count(*) cc FROM MyTable WHERE Defect_Status1 IS NOT NULL AND Closing_Date >= '2011-12-01' AND Closing_Date < '2016-07-01' GROUP BY FORMAT(Closing_Date, 'yyyy_MM') ORDER BY Closing_Month 

通过在GROUP BY添加MONTH(date_column)

 SELECT 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 MONTH(Closing_Date), Category 

您可以使用Year(),Month()Day()和datepart()来完成此操作。

在你的例子中,这将是:

 select 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 Year(Closing_Date), Month(Closing_Date), Category