Home >Database >Mysql Tutorial >How to Sum and Group Data by Month in MySQL?

How to Sum and Group Data by Month in MySQL?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-18 09:39:02757browse

How to Sum and Group Data by Month in MySQL?

How to Sum and Group Data by Date in MySQL

To add up the total values for each month and group them by month, you can use the following SQL query:

SELECT MONTHNAME(o_date), SUM(total) 
FROM theTable
GROUP BY YEAR(o_date), MONTH(o_date)

This query first extracts the month name from the o_date column using the MONTHNAME() function. It then uses the SUM() function to add up the total values for each month. Finally, it groups the results by the year and month of the o_date column using the GROUP BY clause.

The output of this query will be a new table with two columns:

  • MONTHNAME(o_date): The name of the month
  • SUM(total): The total value for the month

Using your sample data, this query will produce the following output:

MONTHNAME(o_date) SUM(total)
January 138
February 88.2
April 29.84

The above is the detailed content of How to Sum and Group Data by Month in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn