Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group by month from Date field using sql

How can I group only by month from a date field (and not group by day)?

Here is what my date field looks like:

2012-05-01 

Here is my current 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 
like image 906
user1858332 Avatar asked Jan 28 '13 15:01

user1858332


People also ask

How do I get the month from a date in SQL?

Simple Query: SELECT DATEADD(m, DATEDIFF(m, 0, GETDATE()), 0) -- Instead of GetDate you can put any date.

How do I GROUP BY month and year in SQL Server?

You can group month and year with the help of function DATE_FORMAT() in MySQL. The GROUP BY clause is also used.

Can you GROUP BY date in SQL?

1 Answer. You can use DATE_FORMAT operator. If you are using this you can easily group the date, timestamp or datetime column using whatever format you want.


1 Answers

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 group by the first of every month, so

`DATEADD(MONTH, DATEDIFF(MONTH, 0, '20130128'), 0)`  

will give '20130101'. I generally prefer this method as it keeps dates as dates.

Alternatively you could 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 what your desired output is. (Closing Year is not necessary in your example, but if the date range crosses a year boundary it may be).

like image 89
GarethD Avatar answered Sep 17 '22 13:09

GarethD