Home >Database >Mysql Tutorial >How Can I Calculate Total Amounts for Each Category Using MySQL's GROUP BY and SUM()?

How Can I Calculate Total Amounts for Each Category Using MySQL's GROUP BY and SUM()?

Barbara Streisand
Barbara StreisandOriginal
2025-01-06 03:55:44962browse

How Can I Calculate Total Amounts for Each Category Using MySQL's GROUP BY and SUM()?

Group Sum Aggregation in MySQL

In data analysis, it's often necessary to aggregate data and calculate sums based on specific criteria. MySQL's GROUP BY clause combined with the SUM() function provides a convenient way to compute such aggregations.

Consider a scenario where you have a table containing a column called cat_name representing categories and a corresponding amount column representing values for each category. The objective is to determine the total amount associated with each category.

To achieve this, you can employ the following query:

SELECT cat_name, SUM(amount) AS total_amount
FROM table
GROUP BY cat_name

This query first groups the rows in the table by the cat_name column. This step partitions the data into separate subgroups based on category values.

Subsequently, the SUM() function is applied to the amount column within each group. It calculates the sum of amount values for each category, effectively providing the total amount for each corresponding cat_name.

The result of the query will be a new table that contains two columns: cat_name and total_amount. Each row in the output table represents a unique category along with the total amount associated with that category.

The above is the detailed content of How Can I Calculate Total Amounts for Each Category Using MySQL's GROUP BY and SUM()?. 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