-1

我有下表我想写一个查询:

表名:Stats_State_County

Column name    Type     Constraint 
-----------------------------------
Population     number 
CountyName     string
State          number   Primary key

我想找到每个州人口最多的县。我只想打印出该县的名称和该县的最大人口。目前,我有一些东西可以返回州及其最大人口,但我需要返回县名而不是州名。

谢谢

4

2 回答 2

0

使用 SQLite 3.7.11 或更高版本,您可以使用:

SELECT CountyName,
       MAX(Population)
FROM Stats_State_County
GROUP BY State

在早期的 SQLite 版本中,不能保证 like 非聚合字段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
于 2013-04-16T07:24:39.770 回答
-1

使用协同子查询来确定同一州内一个县的最大人口。

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 被删除。如果同一个县存在于人口相同的两个州,除非您将州添加到选择并按...分组,否则您可能不会得到您想要的结果...

于 2013-04-15T22:20:41.197 回答