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

142
Visualizações
Get one maximum value per group

I need to preserve one row per group of names from table:

ID | Name  | Attribute1| Attribute2 | Attribute3
 1 | john  | true      | 2012-20-10 | 12345670
 2 | john  | false     | 2015-20-10 | 12345671
 3 | james | false     | 2010-02-01 | 12345672
 4 | james | false     | 2010-02-03 | 12345673
 5 | james | false     | 2010-02-06 | 12345674
 6 | sara  | true      | 2011-02-02 | 12345675
 7 | sara  | true      | 2011-02-02 | 12345676

...according to specified criteria. In first place should be preserved rows with true in Attribute1 (if present), then with max date (Attribute2), and if that's not result in one row - the one with max Attribute3.

Desired result is:

ID|Name|Attribute1|Attribute2|Attribute3
1 | john  | true  | 2012-20-10 | 12345670
5 | james | false | 2010-02-06 | 12345674
7 | sara  | true  | 2011-02-02 | 12345676

I tried to do that with nested joins, but that seems to be overly complicated. Some simply solution is to first do the SQL result of ORDER BY:

CREATE TABLE output AS
SELECT 
    ID, 
    Name,
    Attribute1,
    Attribute2,
    Attribute3
FROM input 
ORDER BY 
    Name,
    Attribute1 DESC, 
    Attribute2 DESC, 
    Attribute3 DESC;

and do the loop for each row and check and cache if name occurred before - if not, preserve it (and cache name in some global variable), else delete row.

Is there any other pure SQL solution?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

For Postgresql:

select distinct on (name) *
from t
order by name, attribute1 desc, attribute2 desc, attribute3 desc

https://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT

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