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

140
Views
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 answers
Answer question

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 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!