Home > Database > Mysql Tutorial > How to Calculate the Sum of Values Grouped by Categories using SQL's GROUP BY?

How to Calculate the Sum of Values Grouped by Categories using SQL's GROUP BY?

Mary-Kate Olsen
Release: 2025-01-04 13:30:40
Original
1034 people have browsed it

How to Calculate the Sum of Values Grouped by Categories using SQL's GROUP BY?

SQL Group by SUM: Calculate Sum of Values Grouped by Categories

In relational database management systems (RDBMS) like MySQL, it's often necessary to aggregate data and compute summary statistics. A common task is to calculate the total of a particular column, grouped by a specific category. This can be achieved using the SQL GROUP BY clause.

Suppose you have a table named category with columns cat_name and amount. Each row represents a category and the corresponding amount associated with it. The goal is to determine the total amount for each unique cat_name.

To solve this problem using MySQL, we can employ the following query:

SELECT cat_name, SUM(amount) AS total_amount
FROM category
GROUP BY cat_name;
Copy after login

This query starts by selecting the cat_name as the first column, which represents the unique category names. It then calculates the sum of the amount column for each unique cat_name and assigns the result to the column total_amount. The GROUP BY clause is used to group the rows by cat_name, ensuring that the total is calculated separately for each distinct category.

Executing this query will return a result set with the category names and their corresponding total amounts, allowing you to analyze the distribution of values across different categories.

The above is the detailed content of How to Calculate the Sum of Values Grouped by Categories using SQL's GROUP BY?. 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