0

There's a table which is called cities and looks like so:

id | city | population | year

I simply need:

For each city select maximal amount of population and year of that maximal population. A solution without nested queries is preferred

So I tried this:

SELECT `city`, MAX(`year`), MAX(`population`) FROM `cities` GROUP BY `city`

But it gives wrong results. What am I doing wrong?

3
  • 1
    You don't need MAX(year) you just need SELECT city, year, MAX(population) FROM cities GROUP BY city Commented May 18, 2015 at 12:32
  • can you provide the sample output, like what you were expecting and what you got?
    – Mukund
    Commented May 18, 2015 at 12:32
  • MySQL? Please tag, since MySQL has it's own ways...
    – jarlh
    Commented May 18, 2015 at 12:36

1 Answer 1

2

1st you have to take max population than you need take max year for that population . Try this:

SELECT C.city, max(C2.year), C.MAX_population
FROM 
(SELECT city, MAX(population) AS MAX_population FROM cities GROUP BY city) C
JOIN cities C2 on C2.city = C.city and C2.population = C.MAX_population
GROUP BY C.city, C.MAX_population
1
  • Is it possible to do the same without nested queries?
    – Yang
    Commented May 18, 2015 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.