Search code examples
mysqlsqlcalculated-columns

mySQL: Can I add a calculated column with the sum of all other rows that have that same shared value


I have a data set where each record includes street, zipcode, city, population. I want to find (% of population one zipcode is to the entire city's population) but can't figure out how to group by zip and then add a column that shows total city's population for every zip with that same city.

[Ex Trying to find (Sum_of_City and Percent_of_City)]

Code I tried:

SELECT
   city,
   zipcode,
   sum(population) as Pop_Count_ (
   SELECT
      SUM(zSUM) 
   FROM
      (
         SELECT
            SUM(Distinct zipcode) AS zCount 
         FROM
            myTable 
         GROUP BY
            city
      )
      AS A)_ 
   FROM
      myTable_ 
   GROUP BY
      city,
      zipcode;

Solution

  • Use window functions:

    select city, zipcode, sum(population) as population,
           sum(population) / sum(sum(population)) over (partition by city) as zipcode_ratio
    from t
    group by city, zipcode;