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
I used the FORMAT function to accomplish this:
You can do this by using Year(), Month() Day() and datepart().
In you example this would be:
I would use this:
This will group by the first of every month, so
will give
'20130101'
. I generally prefer this method as it keeps dates as dates.Alternatively you could use something like this:
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).
By Adding
MONTH(date_column)
inGROUP BY
.DATEPART function doesn't work on MySQL 5.6, instead use MONTH('2018-01-01')