SQL | find max, min population city names by state | SQL Interview Question |

Поділитися
Вставка
  • Опубліковано 4 лют 2025

КОМЕНТАРІ • 2

  • @nikhilshinde8067
    @nikhilshinde8067 11 днів тому +2

    select * from (
    select p1.state,p1.city as maxPopulation ,p2.city as minPopulation,
    row_number() over (partition by p1.state order by p1.state, p1.population-p2.population desc)as rn
    from CityPopulation p1
    inner join CityPopulation p2
    on p1.state = p2.state
    and p1.population > p2.population
    ) where rn=1 ;
    ----
    SELECT DISTINCT
    p1.state,
    FIRST_VALUE(p1.city) OVER (PARTITION BY p1.state ORDER BY p1.population DESC) AS MaxPopulation,
    FIRST_VALUE(p2.city) OVER (PARTITION BY p1.state ORDER BY p2.population ASC) AS minPopulation
    FROM
    CityPopulation p1
    INNER JOIN
    CityPopulation p2 ON p1.state = p2.state AND p1.population > p2.population;

    • @CodeSQL
      @CodeSQL  9 днів тому

      Many thanks for contributing this solution! 🙌