Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Group By and Sum total value of other column

I have 2 columns like this:

+----------+--------+ |   word   | amount | +----------+--------+ | dog      |      1 | | dog      |      5 | | elephant |      2 | +----------+--------+ 

I want to sum the amounts, to get the result

+----------+--------+ | dog      |      6 | | elephant |      2 | +----------+--------+ 

What I have tried so far (and failed) is this:

SELECT word, SUM(amount) FROM `Data` Group By 'word' 
like image 706
Joe Avatar asked Feb 24 '13 05:02

Joe


People also ask

How do I sum values based on criteria in another column in MySQL?

You can use the SUM() function in a SELECT with JOIN clause to calculate the sum of values in a table based on a condition specified by the values in another table.

Can we use sum with GROUP BY?

SUM is used with a GROUP BY clause. The aggregate functions summarize the table data. Once the rows are divided into groups, the aggregate functions are applied in order to return just one value per group. It is better to identify each summary row by including the GROUP BY clause in the query resulst.

How do I sum a group in MySQL?

MySQL SUM() function with group by MySQL SUM() function retrieves the sum value of an expression which has undergone a grouping operation by GROUP BY clause.

How do I sum by GROUP BY data in SQL?

The SQL GROUP BY Statement The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.


1 Answers

Remove the single quote around the WORD. It causes the column name to be converted as string.

SELECT word, SUM(amount)  FROM Data  Group By word 
like image 51
John Woo Avatar answered Sep 24 '22 04:09

John Woo