简体   繁体   中英

SQL return data related to the corresponding MAX() value

I´ve a problem with a SQL query. My database look like this:

State   | City         | Population
-----------------------------------
Texas   | Austin       | 865.00
Texas   | Houston      | 2.200.00
Florida | Jacksonville | 840.000
Florida | Miami        | 417.000
...     | ...          | ...

Now i want to know the maximum population of a state and the related city like this:

OUTPUT:
 State   | City         | Population
 -----------------------------------
 Texas   | Houston      | 2.200.00
 Florida | Jacksonville | 840.000
 ...     | ...          | ...

How can i do this?

EDIT: I use MSAcces 2013, Table name: TPopulation. Sorry for the confusion.

This method allows for ties although those are pretty unlikely here.

-- overall
select t1.State, t1.City, t1.Population
from T as t1
where Population = (
    select max(t2.Population) from T as t2
)

-- per state
select t1.State, t1.City, t1.Population
from T as t1
where t1.Population = (
    select max(t2.Population) from T as t2 where t2.State = t1.State
)

Note that this will return multiple cities per state, if the max population is the same for more than one city per state.

MS ACCESS:

SELECT 
  T1.State,
  T1.City,
  T1.Population
FROM
  TPopulation AS T1
WHERE
  T1.Population =
    (SELECT MAX(T2.Population) FROM TPopulation AS T2 WHERE T2.State = T1.State)

ANSI:

SELECT
    MaxP.State,
    S.City,
    S.Population
FROM
    (
    SELECT
        State,
        MAX(Population)
    FROM
        TPopulation
    GROUP BY
        State
    ) AS MaxP
    INNER JOIN TPopulation AS S ON
        S.State = MaxP.State
        AND S.Population = MaxP.Population
ORDER BY
    MaxP.State ASC,
    S.City ASC

This is my code. It shows the right order, the biggest city first in each state. But it shows every city in each state and I only want the biggest city in each state:

SELECT State, City, Population
FROM TPopulation
ORDER BY State DESC , Population DESC;

OUTPUT:
State   | City         | Population
-----------------------------------
Texas   | Houston      | 2.200.00
Texas   | Austin       | 865.00
Florida | Jacksonville | 840.000
Florida | Miami        | 417.000
...     | ...          | ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM