如何进行原始 SQL 查询以选择与区号关联的人口最多的城市(有重复的区号)

How to make a raw SQL query that selects the city with the highest population associated with an area code (there are duplicate area codes)

我有一个包含以下列的 table: areaCode zipcode city state population

有多行具有与不同 cities/zip 代码关联的相同区号。 我需要select区号对应的人口最多的城市

EX:

area_codes/zip/城市/州/人口

858 94111   San Francisco   CA  3905
858 94121   San Francisco   CA  34786
914 10010   New York    NY  22785
914 10012   New York    NY  17738  

我只想 select 人口为 34786 的城市旧金山(区号为 858)和人口为纽约的行(区号为 914) 22785,因为他们的人口最多。在 select 处理完这些后,我需要创建一个新的 table 并将它们放在一个新的 table 中。

通用解决方案使用 ROW_NUMBER:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY area_codes ORDER BY population DESC) rn
    FROM yourTable
)

SELECT area_codes, zip, city, state, population
FROM cte
WHERE rn = 1;

试试这个:

Create table MaxPopulation as (select area_codes,city,max(population) from table group by area_codes,city);
INSERT INTO cte_new
SELECT 
   area_codes,
   zip,
   city,
   state,
   MAX(population) population
FROM cte
GROUP BY
   area_codes,
   zip,
   city,
   state

通常我更喜欢分组函数而不是 window 函数(分区),因为它提供了更好的性能。我跳过了在此代码

之前您需要的 table 声明