Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda