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;
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!