7

With the following data from a SELECT * FROM (SELECT...) AS foo:

ID    Country   Area
1     US        100
1     UK        200
2     AU        150
2     NZ        250

how can you select the top area and country by ID? So GROUP BY ID and MAX(DESC) but also include the County.

The the result of the query would be:

1     UK     200
2     NZ     250
Robert
  • 25,425
  • 8
  • 67
  • 81
Matt
  • 7,022
  • 16
  • 53
  • 66

2 Answers2

11
SELECT DISTINCT ON (ID)
       ID, Country, Area
FROM   foo
ORDER  BY ID, Area DESC NULLS LAST;

Detailed explanation and links to faster alternatives for special cases:

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
2

Try this

select ID,Country,Area
from (SELECT...) AS foo
WHERE Area = (SELECT MAX(Area)
              FROM (SELECT...) AS foo2
              WHERE foo.ID = foo2.ID )
Robert
  • 25,425
  • 8
  • 67
  • 81