Home >Database >Mysql Tutorial >How to Correctly Use GROUP BY and SUM() in MySQL to Aggregate Data?
How to Group By and Sum Values in Other Columns in MySQL?
In MySQL, the GROUP BY clause is used to aggregate data records based on common values in a specified column. However, if you need to perform calculations on other columns for each group, this can be achieved using aggregation functions like SUM().
Problem:
Given a table with two columns, word and amount, we want to sum the amounts for each unique word.
Failed Attempt:
The query below fails because it incorrectly includes single quotes around the word column in the GROUP BY clause:
SELECT word, SUM(amount) FROM `Data` GROUP BY 'word'
Corrected Solution:
The single quotes around the word column are unnecessary and need to be removed. The correct query to group by the word column and sum the amount column is:
SELECT word, SUM(amount) FROM Data GROUP BY word
Output:
This query will produce the desired output, where the amounts are summed for each unique word:
word | amount |
---|---|
dog | 6 |
elephant | 2 |
The above is the detailed content of How to Correctly Use GROUP BY and SUM() in MySQL to Aggregate Data?. For more information, please follow other related articles on the PHP Chinese website!