Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL SUM when using GROUP BY not working

Let's say we have this table:

Symbol | Size
A      | 12
B      | 5
A      | 3
A      | 6
B      | 8

And we want a view like this:

Symbol | Size
A      | 21
B      | 13

So we use this:

Select Symbol, sum(Size) from table group by Symbol order by Symbol ASC

But instead we get this:

Symbol | Size
A      | 12
B      | 5

What am I doing wrong?!

like image 287
Ant Avatar asked Oct 25 '25 00:10

Ant


1 Answers

You are doing it right, you should expect the correct results. Could you please supply more information about the DB you are using, additional schemas, etc?

Maybe you have some unique index on Symbol?

Try to execute the following to "sanity-test" your system:

SELECT SUM(Size) FROM table

Should result in 34

SELECT Symbol, Count(*) FROM table GROUP BY Symbol

Should results in 3 and 2

If both of the above work perfectly as you noted, please try:

SELECT Symbol, Count(*), Sum(Size) FROM table GROUP BY Symbol

This is your code, with the additions of Count(*) and without the ORDER BY clause. If that does not work after the two above do, I'm really puzzled...

like image 175
Roee Adler Avatar answered Oct 27 '25 20:10

Roee Adler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!