GROUP BY doesn't sum all numeric rows but... I have a workaround.

GROUP BY doesn't sum all numeric rows but... I have a workaround.

Why would you want to sum the numbers of the rows that were grouped by?

The problem:

Let's say we have a database that records the transactions of our user row by row. Like this:

Captura de Tela 2022-04-04 às 15.30.30.png

But we don't want or need to display transaction by transaction. It would be nicer to see the amount of shares the user have by symbol. So we can use GROUP BY, like this:

SELECT * FROM transactions GROUP BY symbol;

Captura de Tela 2022-04-04 às 15.35.24.png

That is much nicer. But as you can see the amount of shares from the symbol aapl (Apple) is 2. But we want to know all the shares the person have in total.

The solution:

SELECT *, SUM(share) AS sum_of_shares FROM transactions GROUP BY symbol;

Captura de Tela 2022-04-04 às 15.39.11.png

Now we have another column that we can see the sum of all the shares the person has grouped by symbol. If we dont use SUM() it will group by the symbol and give the shares from the first row this new symbol appeared.