Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
SQL get sum of a Column in Select

I've got a table like the one shown below.

+------+-------+
|  id  | value |
+------+-------+
| 1    | 5     |
+------+-------+
| 2    | 9     |
+------+-------+
| 1    | 8     |
+------+-------+
| 3    | 10    |
+------+-------+

I'd like to be able to select three entries with the highest value. However, I want the ids to be grouped and the values to be added together. Here's the desired output:

+------+-------+
|  id  | value |
+------+-------+
| 1    | 13    |
+------+-------+
| 3    | 10    |
+------+-------+
| 2    | 9     |
+------+-------+

Currently, I've have this code: SELECT * FROM table GROUP BY id ORDER BY SUM(value) DESC LIMIT 3 It is able to pick the top three rows (sorted by the value column) and group them by the ids. However, it returns with the highest value instead of adding them together, as seen below.

+------+-------+
|  id  | value |
+------+-------+
| 1    | 8     |
+------+-------+
| 3    | 10    |
+------+-------+
| 2    | 9     |
+------+-------+

What should I use to add together the value column on my SELECT statement?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can do:

select *
from (
  select id, sum(value) as total from t group by id
) x
order by total desc
limit 3

Or... in compressed syntax:

select id, sum(value) as total from t group by id order by total desc limit 3

See running example at DB Fiddle.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!