MySQL Group By and Sum Total Value of Other Column
In MySQL, when using the GROUP BY clause to group rows based on one or more columns, it's common to want to calculate aggregate values for other columns. In this example, suppose you have a table with two columns: 'word' and 'amount'. You want to sum the amounts for each unique word.
Issue Encountered:
When attempting to use the GROUP BY clause as follows:
SELECT word, SUM(amount) FROM `Data` GROUP BY 'word'
you may encounter an error stating that the column is invalid.
Solution:
The problem arises because you have enclosed the 'word' column name in single quotes, which causes it to be treated as a string. Instead, simply remove the single quotes around the column name:
SELECT word, SUM(amount) FROM Data GROUP BY word
This corrected syntax will correctly group the rows by the 'word' column and sum the 'amount' column for each unique word, providing the desired result:
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!