Home >Database >Mysql Tutorial >How to Group SQL Data Totals by Date in MySQL?

How to Group SQL Data Totals by Date in MySQL?

Barbara Streisand
Barbara StreisandOriginal
2024-11-16 16:22:03860browse

How to Group SQL Data Totals by Date in MySQL?

Querying SQL Data: Grouping Totals by Date

When working with time-series data, it is often necessary to perform aggregate operations, such as summing values, grouped by a date field. In MySQL, the combination of GROUP BY and date functions allows for efficient grouping and aggregation of data.

To sum the total column by day, use:

SELECT o_date, SUM(total) 
FROM theTable
GROUP BY o_date;

To sum the total column by month, use:

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

This query returns a result set with two columns: the month name and the total sum for that month. The MONTHNAME function converts the numeric month value to a string representing the month name.

The following is the output from the query based on the provided sample data:

Month Total
January 138
February 88.2
April 29.84

The above is the detailed content of How to Group SQL Data Totals by Date 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