使用协同子查询来确定同一州内一个县的最大人口。
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 中选择人口,县 where a1.population >= (Select max(A2.population) from CTE A2 Where A2.State = A1.State) 按人口,县分组
注意:如果两个县的人口相同,则返回两个县。如果一个县由于某种原因被列出两次,它们会通过 group by 被删除。如果同一个县存在于人口相同的两个州,除非您将州添加到选择并按...分组,否则您可能不会得到您想要的结果...