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
Release: 2024-12-29 20:14:21
Original
876 people have browsed it

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

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'
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template