我有一个包含列的表:人口、州和县
我想找到每个州人口最多的县。我也只想打印该县的名称和该县的最大人口。
我怎么能做这样的查询?
您应该能够使用子查询来获取每个州的最大人口,然后使用该结果来确定县:
select t1.county,
t1.population
from yourtable t1
inner join
(
select max(population) MaxPop, state
from yourtable
group by state
) t2
on t1.population = t2.maxpop
and t1.state = t2.state;
您可以使用嵌套查询来执行此操作EXISTS
:
SELECT m1.county, m1.population
FROM mytable m1
WHERE NOT EXISTS (
SELECT 1 -- No other county in the state has more people
FROM mytable m2
WHERE m1.state=m2.state
AND m2.population > m1.population
)
如果单个州的多个县具有相同的population
,则将返回两个县。