22 Votes

MySQL: GROUP BY Day, Month and Year

Question by Compi | Last update on 2023-01-18 | Created on 2016-04-24

I have some data sets with a timestamp column in which the date of the record is specified. Now, I would like to determine the number of entries falling into the period of a specific year, month or day.

How can I implement that using MySQL? I only know that I probably have to use COUNT(id) and GROUP BY, but I have no idea how to write such a query.

ReplyPositiveNegativeDateVotes
3Best Answer5 Votes

COUNT(id) and GROUP BY is a good choice for doing that. In the following example, the date column is "dat".

Here is how to get the number grouped by years:

SELECT COUNT(id), YEAR(dat) FROM tab GROUP BY YEAR(dat);

Here is how to get the number grouped by months:

SELECT COUNT(id), MONTH(dat), YEAR(dat) 
FROM tab GROUP BY YEAR(dat), MONTH(dat);

And here is how to get the number grouped by days:

SELECT COUNT(id), DAY(dat), MONTH(dat), YEAR(dat) 
FROM tab GROUP BY YEAR(dat), MONTH(dat), DAY(dat);

You can read more about that in this tutorial.
Last update on 2023-01-18 | Created on 2016-04-24

ReplyPositive Negative
11 Vote

After group by using month, year and day the data shows as vertical list data...

Is it possible we can transform into horizontal list data?
2017-12-20 at 10:13

ReplyPositive Negative
22 Votes

The easiest way to do this, is just to use the same query but output them rotated.

For example, if using PHP, you can load the result into an array and go through this array as you want.

If you are using MySQL from shell, you can append \G to your query to rotate the result.
2017-12-20 at 13:51

Positive Negative
Reply
Reply

Related Topics

PHP: Current Date and Time

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.