mysql group by month with code examples

MySQL is a popular and powerful open-source relational database management system. It provides various features to manage and organize your data efficiently, including the GROUP BY statement. Grouping data by month is a common requirement in data analysis, and MySQL's GROUP BY clause is perfectly suited for that.

In this article, we'll explore how to group data by month in MySQL, including code examples and explanations.

What is GROUP BY in MySQL?

The GROUP BY clause in MySQL is used to group rows that have the same values into summary rows. It is typically used with aggregate functions such as SUM, COUNT, AVG, MIN, and MAX. The GROUP BY clause follows the SELECT statement and is used to specify the columns upon which the grouping should be performed.

Syntax:

SELECT column_name(s)
FROM table_name
GROUP BY column_name(s);

The GROUP BY clause can accept one or more columns. When grouping by multiple columns, the grouping is performed based on the distinct combination of values in those columns.

Grouping data by month

To group data by month, we need to extract the month from a date column and use it as the group criterion. MySQL provides the MONTH() function that takes a date or datetime value as input and returns the corresponding month number as an integer.

Syntax:

MONTH(date)

Example:

SELECT MONTH('2022-12-31')
-- Output: 12

Now that we know how to extract the month from a date, we can use it in the GROUP BY clause to group data by month. Let's consider an example table of sales data, where each row contains the date of sale and the corresponding amount sold.

CREATE TABLE sales (
  id INT PRIMARY KEY AUTO_INCREMENT,
  sale_date DATE,
  amount DECIMAL(10,2)
);

Suppose we want to group the total sales by month and get the average amount sold per month. Here's how we can do it:

SELECT MONTH(sale_date) AS month, SUM(amount) AS total_sales, AVG(amount) AS avg_sales
FROM sales
GROUP BY month;

Explanation:

  • We select the month extracted from the sale_date column using the MONTH() function and alias it as month.
  • We use the SUM() function to calculate the total sales for each month and alias it as total_sales.
  • We use the AVG() function to calculate the average amount sold for each month and alias it as avg_sales.
  • We group the data by the month column.

Output:

+-------+-------------+------------+
| month | total_sales | avg_sales |
+-------+-------------+------------+
| 1     | 1000.00     | 500.00     |
| 2     | 1200.00     | 600.00     |
| 3     | 800.00      | 400.00     |
+-------+-------------+------------+

In this example, we see that the data is grouped by month, and for each month, we get the total sales and the average amount sold. The MONTH() function is used to extract the month from the sale_date column, and the GROUP BY clause is used to group the data accordingly.

Conclusion

In this article, we learned how to group data by month in MySQL using the GROUP BY clause and the MONTH() function. We saw how to extract the month from a date column and use it as the grouping criterion. We also saw a code example of grouping sales data by month and getting the total sales and average amount sold per month.

By using the GROUP BY clause and other aggregation functions available in MySQL, data analysis becomes simpler and efficient. Grouping by month is just one of the numerous possibilities that the GROUP BY clause offers.

GROUP BY is a widely used clause in SQL that helps to group rows based on one or more columns' values. The primary usage of the GROUP BY clause is mainly associated with generating summary reports, which can give us a better understanding of the data's behavior.

In the previous section, we saw how to group data by month in MySQL with code examples. However, grouping data is not always limited to month, so in this section, let's dive into some more examples to understand the GROUP BY Clause's functionality better.

Grouping data by day and year

We already saw in the previous section of how to group data by month. Similarly, with MySQL's DATE_FORMAT() function, we can extract the day and year from a date column to group data based on day or year.

Syntax:

DATE_FORMAT(date, format)

Example:

SELECT DATE_FORMAT('2022-12-31', '%d')
-- Output: 31

SELECT DATE_FORMAT('2022-12-31', '%Y')
-- Output: 2022

Here, the '%d' and '%Y' are the format options to get the day and the year value.

Now let's consider the sales table having the sales data for each day, which looks like this:

CREATE TABLE sales (
  id INT PRIMARY KEY AUTO_INCREMENT,
  sale_date DATE,
  amount DECIMAL(10,2)
);

Use the following queries to group the data based on day or year respectively:

Group by day:

SELECT DATE_FORMAT(sale_date, '%d') AS day, SUM(amount) AS total_sales
FROM sales
GROUP BY day;

Output:

+-----+-------------+
| day | total_sales |
+-----+-------------+
| 01  | 500.00      |
| 02  | 700.00      |
| 03  | 350.00      |
+-----+-------------+

Group by year:

SELECT DATE_FORMAT(sale_date, '%Y') AS year, SUM(amount) AS total_sales
FROM sales
GROUP BY year;

Output:

+------+-------------+
| year | total_sales |
+------+-------------+
| 2020 | 1500.00     |
| 2021 | 2500.00     |
| 2022 | 1000.00     |
+------+-------------+

Grouping data with multiple columns

We can group rows by multiple columns in a single query by separating them with commas.

Suppose we have a table named orders that contains data of customers, including their name, gender, order date, and order value. To group the data based on the customer's gender, along with the year and month of the order, we can use the following query:

SELECT gender, DATE_FORMAT(order_date, '%Y-%m') AS year_month, SUM(order_value) AS total_sales
FROM orders
GROUP BY gender, year_month;

Output:

+--------+------------+-------------+
| gender | year_month | total_sales |
+--------+------------+-------------+
| Female | 2020-01    | 500.00      |
| Female | 2020-02    | 200.00      |
| Female | 2021-03    | 800.00      |
| Male   | 2020-01    | 1000.00     |
| Male   | 2021-02    | 1800.00     |
| Male   | 2022-01    | 1000.00     |
+--------+------------+-------------+

Here, we can see that the data is grouped by the customer's gender, along with the year and month of the order. This gives us a better understanding of the sales data, as we can analyze the sales trends based on year and month per gender.

Conclusion

In this section, we saw some more examples of how to use the GROUP BY clause in MySQL to group data based on day, year, and multiple columns. We also learned how to extract day and year from a date column using the DATE_FORMAT() function.

The GROUP BY clause, along with other aggregation functions available in MySQL, can help us generate insightful reports and analyze vast amounts of data more efficiently.

Popular questions

  1. What is the GROUP BY clause in MySQL?
    Answer: The GROUP BY clause in MySQL is used to group rows that have the same values into summary rows, typically used with aggregate functions such as SUM, COUNT, AVG, MIN, and MAX.

  2. How can we group data by month in MySQL?
    Answer: We can use the MONTH() function to extract the month from a date or datetime column and use it as the group criterion in the GROUP BY clause.

  3. Can we group data by day and year using the GROUP BY clause in MySQL?
    Answer: Yes, we can use the DATE_FORMAT() function to extract the day and year from a date column and use them as the group criterion in the GROUP BY clause.

  4. Is it possible to group data by multiple columns using the GROUP BY clause in MySQL?
    Answer: Yes, we can group data by multiple columns in a single query by separating them with commas in the GROUP BY clause.

  5. What other aggregation functions are available in MySQL apart from GROUP BY?
    Answer: Some of the available aggregation functions in MySQL are SUM, COUNT, AVG, MIN, MAX, as well as functions for manipulating string and date/time values like CONCAT, SUBSTRING, DATE_FORMAT, etc.

Tag

MySQL Date Grouping

As a senior DevOps Engineer, I possess extensive experience in cloud-native technologies. With my knowledge of the latest DevOps tools and technologies, I can assist your organization in growing and thriving. I am passionate about learning about modern technologies on a daily basis. My area of expertise includes, but is not limited to, Linux, Solaris, and Windows Servers, as well as Docker, K8s (AKS), Jenkins, Azure DevOps, AWS, Azure, Git, GitHub, Terraform, Ansible, Prometheus, Grafana, and Bash.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top