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
Release: 2024-11-16 16:22:03
Original
843 people have browsed it

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;
Copy after login

To sum the total column by month, use:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template