Home >Database >Mysql Tutorial >How to Correctly Use GROUP BY and SUM() in MySQL to Aggregate Data?

How to Correctly Use GROUP BY and SUM() in MySQL to Aggregate Data?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-05 00:59:38937browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn