MySQL: Grouping Data and Summing Column Values
Problem:
Consider the following MySQL table with two columns, word and amount:
word | amount |
---|---|
dog | 1 |
dog | 5 |
elephant | 2 |
The task is to group the data by the word column and sum the corresponding amount values. The desired output is:
word | amount |
---|---|
dog | 6 |
elephant | 2 |
Solution:
The original SQL query:
SELECT word, SUM(amount) FROM `Data` GROUP BY 'word'
contains a minor error. The single quote around the word column name converts it to a string. To fix this, simply remove the single quote:
SELECT word, SUM(amount) FROM Data Group By word
This revised query correctly performs the operation, grouping the data by the word column and summing the amount values for each unique word.
The above is the detailed content of How to Group Data and Sum Values in MySQL?. For more information, please follow other related articles on the PHP Chinese website!