简体   繁体   English

SQL返回与相应的MAX()值有关的数据

[英]SQL return data related to the corresponding MAX() value

I´ve a problem with a SQL query. 我有一个SQL查询问题。 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. 编辑:我使用MSAcces 2013,表名称: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: MS访问:

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: 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
...     | ...          | ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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