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

时间:2015-04-28 20:12:06

标签: sql ms-access max

我的SQL查询有问题。我的数据库看起来像这样:

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

现在我想知道一个州和相关城市的最大人口数量:

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

我该怎么做?

编辑:我使用MSAcces 2013,表名:TPopulation。对不起,感到困惑。

3 个答案:

答案 0 :(得分:2)

这种方法允许联系,虽然这些不太可能。

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

答案 1 :(得分:0)

请注意,如果每个州的多个城市的最大人口数相同,则每个州将返回多个城市。

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

答案 2 :(得分:0)

这是我的代码。它显示了正确的顺序,是每个州最大的城市。但它显示了每个州的每个城市,我只想要每个州最大的城市:

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