Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda