0

I have a table that has the following columns: areaCode zipcode city state population

There are multiple rows with the same area codes that are associated with different cities/zip codes. I need to select the city with the highest population that corresponds to the area code.

EX:

area_codes / zip / city / state / population

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

I want to be able to only select the city San Francisco (with area code of 858) that has the population of 34786 and the row New York (with area code of 914) that has the population of 22785, since they have the highest populations. After selecting these ones I need to create a new table and place them in a new table.

sbuck89
  • 123
  • 3
  • 6

3 Answers3

1

A general solution uses 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;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Try This:

Create table MaxPopulation as (select area_codes,city,max(population) from table group by area_codes,city);
Naveen Kumar
  • 1,988
  • 1
  • 7
  • 11
1
INSERT INTO cte_new
SELECT 
   area_codes,
   zip,
   city,
   state,
   MAX(population) population
FROM cte
GROUP BY
   area_codes,
   zip,
   city,
   state

Generally I would prefer a grouping function than a window function (parition) since it offers a much better performance. I have skipped the table declaration that you would require before this code

A_kat
  • 1,459
  • 10
  • 17