我有下表我想写一个查询:
表名:Stats_State_County
Column name Type Constraint
-----------------------------------
Population number
CountyName string
State number Primary key
我想找到每个州人口最多的县。我只想打印出县名和该县的最大人口数。目前,我有一些东西可以返回州和他们的最大人口,但我需要返回县名而不是州。
由于
答案 0 :(得分:0)
使用SQLite 3.7.11或更高版本,您可以使用:
SELECT CountyName,
MAX(Population)
FROM Stats_State_County
GROUP BY State
在早期的SQLite版本中,不保证像CountName
这样的非聚合字段来自与MAX
匹配的相同记录,因此您必须从一个字段中查找名称。单独的步骤:
SELECT (SELECT CountyName
FROM Stats_State_County
WHERE State = T1.State
AND Population = T1.MaxPop),
MaxPop
FROM (SELECT State,
MAX(Population) AS MaxPop
FROM Stats_State_County
GROUP BY State
) AS T1
答案 1 :(得分:-1)
使用coorleated子查询来识别同一州内的县的最大人口。
With CTE as
(Select 'A' as state,1000 as population, 'A1' as county FROM DUAL UNION ALL
Select 'A',1000, 'A2' FROM DUAL UNION ALL
Select 'A',1001, 'A3' FROM DUAL UNION ALL
Select 'A',1001, 'A3' FROM DUAL UNION ALL
Select 'A',1001, 'A4' FROM DUAL UNION ALL
Select 'B',2000, 'B1' FROM DUAL UNION ALL
Select 'B',2000, 'B3' FROM DUAL UNION ALL
Select 'B',2001, 'B2' FROM DUAL UNION ALL
Select 'B',2002, 'B4' FROM DUAL)
Select population, county from CTE A1
where a1.population >= (Select max(A2.population) from CTE A2 Where A2.State = A1.State) Group by population, county
返回:
Population County
1001 A3
1001 A4
2002 B4
在此选择的两种情况下,将CTE替换为您的表名,您应该没问题。
从CTE A1中选择人口,县 其中a1.population> =(从CTE A2中选择最大值(A2。人口)A2.State = A1.State)按人口,县分组
注意:如果两个县有相同的人口,则返回两个县。如果一个县由于某种原因被列出两次,那么它们将被移除。如果同一个县存在于具有相同人口的两个州中,除非您通过...添加状态到select和group,否则您可能无法获得所需的结果。