-->

MySQL: how to sum up vaues of rows and sort the re

2019-04-14 00:53发布

问题:

I'm looking for a SQL-statement that sums up some specific values and sorts the result. To be more clear: I have a table that consists of identifiers and values:

id     val
ab     10
ab     12
ab      3
cd     25
cd     10
ef      2
ef      7

Here all values for ab, cd and ef have to be summed up and ordered by result so that I get the following:

cd     35
ab     25
ef      9

So is there a SQL-statement that performs that task in one go?

回答1:

SELECT id, SUM(val) as total
FROM your_table
GROUP BY id
ORDER BY total DESC;


回答2:

Use group function sum:

select id, sum(val) as val from my_table group by id order by 2 desc