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
Answer from John Woo on Stack Overflow
🌐
w3resource
w3resource.com › mysql › aggregate-functions-and-grouping › aggregate-functions-and-grouping-sum-with-group-by.php
>MySQL sum() with group by - w3resource
mysql> SELECT cate_id,SUM(total_cost) -> FROM purchase -> GROUP BY cate_id; +---------+-----------------+ | cate_id | SUM(total_cost) | +---------+-----------------+ | CA001 | 1725.00 | | CA002 | 965.00 | | CA003 | 900.00 | +---------+-----------------+ 3 rows in set (0.00 sec)
Discussions

[MySQL] Having some trouble with my Group By and SUM statement
Well de-duping the rows is easy, it's just a simple DISTINCT. Or if you're really keen on grouping, then a MIN() or MAX() aggregate function will give you the total without summing it. But if you're saying there's other rows for the same PO Number and Invocie Number with different totals that need to be summed, then you can do the aforementioned in a subquery or CTE, to de-dupe first, then group again and use SUM() to get your distinct actual totals. More on reddit.com
🌐 r/SQL
11
2
April 3, 2025
mysql - SUM() ignores GROUP BY and sums up 4 rows instead of 2 - Database Administrators Stack Exchange
I'm having difficulty with GROUP BY in MySQL. My database setup: client_visit - id - member_id - status_type_id (type_of_visit table) - visit_starts_at - visit_ends_at member... More on dba.stackexchange.com
🌐 dba.stackexchange.com
mysql - How do I sum a specific column with group by and also sum a specific column without group by? - Stack Overflow
I have a sample table here, the columns are transaction_id, total_amount, collected_amount. transaction_id total_amount collected_amount 1 100 60 1 100 40 2 40 30 2 40 10 3 50 50 4 20 20 More on stackoverflow.com
🌐 stackoverflow.com
mysql - Group by date and sum of all unique values - Stack Overflow
I'm trying to write a SQL query for this report to group by date and also get the count of all unique values. The problem I have is that I do not know how many unique values I will have ahead of ti... More on stackoverflow.com
🌐 stackoverflow.com
🌐
W3Schools
w3schools.com › mysql › mysql_groupby.asp
MySQL GROUP BY Statement
The GROUP BY statement is almost always used in conjunction with aggregate functions, like COUNT(), MAX(), MIN(), SUM(), AVG(), to perform calculations on each group.
🌐
DataCamp
datacamp.com › doc › mysql › mysql-sum
MySQL SUM() Function: Usage & Examples
Combine with GROUP BY. Use `SUM()` with `GROUP BY` for grouped totals to gain insights into data segments.
🌐
Reddit
reddit.com › r/sql › [mysql] having some trouble with my group by and sum statement
r/SQL on Reddit: [MySQL] Having some trouble with my Group By and SUM statement
April 3, 2025 -

Trying to get a bit of code working for work, and I'm having trouble with the SQL part.

Customer has a database table - not a real relational DB, it's a staging table. It is designed to hold invoice line data for export to another software. I need to make a SELECT statement to show the sum of all the invoice totals, per purchase order.

However, the problem lies in that on EACH LINE, the Invoice Total is shown. Because their accounting software needs that, I guess. So if an invoice has 5 lines, you get 5 totals, and if I just did a simple SUM(), it'd be inaccurate.

(The lines also show each line total, but NOT the taxes, so I can't just add those up or it'd be short.)

My table is something like this:

PO Number Invoice Number Invoice Total
1001 ABC 1000.00
1001 ABC 1000.00
1001 DEF 120.00
1001 GHI 75.99
1002 IJK 35.99
1003 JKL 762.33

Hope this makes sense. So Invoice ABC is NOT $2000, it's $1000. So I need to somehow de-dupe the "duplicate" rows, and add up the totals after tat, but I can't quite figure it out.

My best attempts have gotten me to the point where it will give me double (or triple, or quadruple etc) amounts.

🌐
MySQL
dev.mysql.com › doc › refman › 9.7 › en › group-by-modifiers.html
MySQL :: MySQL 9.7 Reference Manual :: 14.19.2 GROUP BY Modifiers
ORDER BY and ROLLUP can be used together, which enables the use of ORDER BY and GROUPING() to achieve a specific sort order of grouped results. For example: mysql> SELECT year, SUM(profit) AS profit FROM sales GROUP BY year WITH ROLLUP ORDER BY GROUPING(year) DESC; +------+--------+ | year | profit | +------+--------+ | NULL | 7535 | | 2000 | 4525 | | 2001 | 3010 | +------+--------+
🌐
OneUptime
oneuptime.com › home › blog › how to use the sum() function in mysql
How to Use the SUM() Function in MySQL
March 31, 2026 - -- Revenue per customer SELECT customer_id, SUM(total) AS total_spent FROM orders GROUP BY customer_id ORDER BY total_spent DESC; -- Units sold per product SELECT product_id, SUM(quantity) AS units_sold FROM order_items GROUP BY product_id ORDER BY units_sold DESC LIMIT 10;
Find elsewhere
🌐
Substack
openlamptech.substack.com › multi-level aggregation using mysql group by with rollup
Multi-level Aggregation Using MySQL GROUP BY WITH ROLLUP
April 12, 2022 - SELECT MONTHNAME(payment_date) AS month_name, DAYNAME(payment_date) AS day_name, SUM(amount) AS total FROM payment WHERE MONTH(payment_date) IN(2,5) GROUP BY MONTHNAME(payment_date), DAYNAME(payment_date) WITH ROLLUP; ... Rows with a NULL value for the 'day_name' column has summary totals at the month level in the 'total' column. The MySQL documentation refers to rows like these as having super-aggregation.
Top answer
1 of 2
3

As Willem Renzema said, you've misunderstood how GROUP BY works. Since it doesn't seem like you've understood what he said, let me try saying it a little differently.

GROUP BY, logically enough, is used to group together rows from your result set. Normally you provide a list of the columns to use to group your rows together. GROUP BY sch.id, cv.member_id tells SQL to identify the unique sets of values for those two columns, and to group the rows in the result set by those values. In your case, there are two unique value pairs for those two values:

  • cv.member_id = 82, sch.id = 17101
  • cv.member_id = 82, sch.id = 17153

So, you'll get two groups of rows - three that have the first pair of values, and one that has the second pair.

Adding additional columns to a GROUP BY clause will never result in fewer groups - either the new column(s) are the same in all rows (in which case you have the same number of groups), or the new column(s) have different values form some rows in one or more of hour original groups (in which case, you'll now have more groups).

Also (as pointed out by Willem), you've got a syntax error. The columns in a GROUP BY list are separated by commas. In your GROUP BY sch.id AND cv.member_id, you're grouping by a calculation: sch.id AND cv.member_id, or the result of treating both sch.id and cv.member_id as if they were Boolean values. Since neither is 0, when converted to Booleans both evaluate to 1 (true), and the combination (true AND true) is true. So, you wind up with just one group, of 4 rows.

Let's step back, and consider what (it looks like) you're actually trying to do. For a given member_id, you want the total time they're involved in activities of the types "Booked" or "Present".

Note that the total time is calculated out of the schedule_event table. Also, note that a given member_id can be associated with the same schedule_event more than once. So, to get total time, we need to identify the distinct schedule_event rows that our member_id is tied to, and sum the time for those unique values.

That being the case, the simplest way to proceed is to use a sub-query to get the list of distinct schedule_events our member_id is tied to, and then sum the total times for those distinct events.

Here's a query that will do just that:

SELECT `member_id`
      ,SUM(`totalTime`) as `totalTime`
  FROM (
        SELECT DISTINCT
            cv.member_id AS `member_id`,
            sch.id AS `scheduleId`,
            TIMESTAMPDIFF(SECOND, sch.starts_at, sch.ends_at) AS `totalTime`
        FROM 
            `schedule_event` AS `sch`
            INNER JOIN `client_visit` AS `cv` ON cv.schedule_event_id = sch.id
            INNER JOIN `type_of_visit` AS `tov` ON tov.id = cv.status_type_id
        WHERE 
            (tov.type = 'TYPE_BOOKED' OR tov.type = 'TYPE_PRESENT') 
            AND cv.member_id = 82
       ) sq
 GROUP BY `member_id`;

The subquery (imaginatively labeled sq) is basically your original query. I changed your LEFT JOIN to an INNER JOIN, as we must have a client_visit record to identify both the member_id, and the type of visit. However, I removed the SUM on totalTime; at this point, we just want to know the time each schedule_event will take. I also added DISTINCT - we don't care how many time this schedule_event appears with this member_id; the total time will be the same whether it shows up once, three times, or 207 times.

Once we've identified the schedule_event data that our member_id is connected to, then we want the total time for all those schedule_event rows. So, we take the results of the sub-query, group them by member_id (in case it would ever be necessary to pull this back for multiple member_id values), and sum up the calculated times for each schedule_event row.

Since joanolo had goen to the trouble to set up a dbfiddle for your problem, I took his work and added this query at the end, so you could see the results were what you wanted; the updated dbfiddle link is here.

I hope this helps clarify how GROUP BY actually works for you.

2 of 2
7

I believe you have a misunderstanding of what GROUP BY does. Not surprising, I had issues myself when first learning, in large part because the MySQL manual doesn't actually explicitly say what GROUP BY does, at least not that I can find (and I searched a lot, just now; plenty of caveats and special behavior, not so much an actual definition).

My (on the fly) Definition:

GROUP BY condenses your SELECT results so that only 1 row is returned for each distinct combination of values for the columns specified in the GROUP BY clause. In that sense, it is similar to DISTINCT, but works on the columns in the GROUP BY instead of the SELECT statement.

In non-MySQL land, you can only SELECT columns you specify in your GROUP BY clause, PLUS any aggregate functions you want. Those aggregate functions, including SUM, operate on a per row basis, reporting a result ONLY for the now "hidden" extra rows.

As you can see, that is what your query is actually doing (or would be, but I think you gave an inaccurate example, as ypercube points out in the comments). It is summing up all the now-hidden extra rows, and reporting their total, for the given sch.id.

If you want the total of only distinct values of each sch.id, you'll have to do things differently to get the information you want.

One reason that it is not simple, is MySQL has no idea WHICH row you want to include in the sum. They may be all the same in your example (8100), but there's no guarantee of that.

Since MySQL allows you to select columns that are neither specified in the GROUP BY clause nor are aggregate functions, it essentially chooses one at "random" and displays it to you. While not actually random, it is non-deterministic, and can change at any time for the same query and data, even if it appears to you to always give the same result.

So, before you can proceed, you need to decide how you want to determine which row for each sch.id contains the value you want to sum.

If you know the values to always be the same, then one simple (although not necessarily optimized) solution is to wrap your original GROUP BY query in another query (making the original a subquery) and then use the SUM function in the outer query, without a GROUP BY clause. The subquery will remove your duplicates, and the outer query will sum up the total of the de-duplicated rows.

🌐
MySQL
dev.mysql.com › doc › refman › 8.4 › en › aggregate-functions.html
MySQL :: MySQL 8.4 Reference Manual :: 14.19.1 Aggregate Function Descriptions
Those that can be used this way are signified in their syntax description by [over_clause], representing an optional OVER clause. over_clause is described in Section 14.20.2, “Window Function Concepts and Syntax”, which also includes other information about window function usage. For numeric arguments, the variance and standard deviation functions return a DOUBLE value. The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or DECIMAL), and a DOUBLE value for approximate-value arguments (FLOAT or DOUBLE).
🌐
TutorialsPoint
tutorialspoint.com › mysql › mysql_aggregate_functions_sum.htm
MySQL - SUM() Function
The MySQL SUM() function is an aggregate function that is used to calculate the sum of all values in a particular column/field. If the specified row(s) doesn't exist this function returns NULL.
🌐
GeeksforGeeks
geeksforgeeks.org › mysql › sum-function-in-mysql
SUM() Function in MySQL - GeeksforGeeks
March 27, 2026 - This example filters grouped results based on total quantity. It is used after GROUP BY to apply conditions on aggregated values. ... SELECT product_name, SUM(quantity) AS total_quantity FROM sales GROUP BY product_name HAVING SUM(quantity) > 10;
🌐
MySQL
dev.mysql.com › doc › refman › 9.7 › en › aggregate-functions.html
MySQL :: MySQL 9.7 Reference Manual :: 14.19.1 Aggregate Function Descriptions
Those that can be used this way are signified in their syntax description by [over_clause], representing an optional OVER clause. over_clause is described in Section 14.20.2, “Window Function Concepts and Syntax”, which also includes other information about window function usage. For numeric arguments, the variance and standard deviation functions return a DOUBLE value. The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or DECIMAL), and a DOUBLE value for approximate-value arguments (FLOAT or DOUBLE).
🌐
Stack Overflow
stackoverflow.com › questions › 67291833 › how-do-i-sum-a-specific-column-with-group-by-and-also-sum-a-specific-column-with
mysql - How do I sum a specific column with group by and also sum a specific column without group by? - Stack Overflow
And also the sum of collected_amount (without group by, just use the SQL SUM function) Here is the expected output. ... As per the question guide, please DO NOT post images of code, data, error messages, etc. - copy or type the text into the question. Please reserve the use of images for diagrams or demonstrating rendering bugs, things that are impossible to describe accurately via text. ... Ok. I'll convert it to text. On your other question, it is mysql.
🌐
Stack Overflow
stackoverflow.com › questions › 55668608 › group-by-date-and-sum-of-all-unique-values › 55672660
mysql - Group by date and sum of all unique values - Stack Overflow
SELECT date, SUM(CASE WHEN name='John' THEN 1 ELSE 0 END) AS John, SUM(CASE WHEN name='Sylvia' THEN 1 ELSE 0 END) AS Sylvia FROM myTable GROUP BY date;
🌐
YouTube
youtube.com › watch
Uso de la funcion GROUP BY y SUM en Mysql y PhpMyadmin(Codigo) - YouTube
En este video realizaremos dos ejercicios para aprender a utilizar la función Group BY para agrupar todas la filas por un solo campo y/o atributo de nuestra ...
Published: October 27, 2020
🌐
YouTube
youtube.com › watch
Sum of values of columns in MySQL table with GROUP BY , IN and CASE - YouTube
https://www.plus2net.com/sql_tutorial/sql_sum-multiple.phphttps://www.plus2net.com/sql_tutorial/sql_sum.phpWe can get sum of all values of a particular colum
Published: September 6, 2020
🌐
YouTube
youtube.com › watch
MySQL: GROUP BY
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
W3Schools
w3schools.com › sql › sql_Groupby.asp
SQL GROUP BY Statement
String Functions: Asc Chr Concat ... SQL Syllabus SQL Study Plan SQL Training ... The GROUP BY statement is used to group rows that have the same values into summary rows, like "Find the number of customers in each ...