w3resource

MySQL SUM() function with group by

SUM() function with group by

MySQL SUM() function retrieves the sum value of an expression which has undergone a grouping operation by GROUP BY clause.

Example:

Sample table: purchase


Code:

SELECT cate_id,SUM(total_cost)
FROM purchase            
GROUP BY cate_id;

Relational Algebra Expression:

Relational Algebra Expression: MySQL SUM() function with group by.

Relational Algebra Tree:

Relational Algebra Tree: MySQL SUM() function with group by.

Explanation:

The above MySQL statement returns the sum of 'total_cost' from purchase table for each group of category ('cate_id') .

Output:

mysql> SELECT cate_id,SUM(total_cost)
    -> FROM purchase            
    -> GROUP BY cate_id;
+---------+-----------------+
| cate_id | SUM(total_cost) |
+---------+-----------------+
| CA001   |         1725.00 | 
| CA002   |          965.00 | 
| CA003   |          900.00 | 
+---------+-----------------+
3 rows in set (0.00 sec)

Previous: SUM()
Next: VAR_POP()



Follow us on Facebook and Twitter for latest update.