简体   繁体   English

mySQL:我可以添加一个计算列,其中包含具有相同共享值的所有其他行的总和吗

[英]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.我想找到(一个邮政编码占整个城市人口的人口百分比)但无法弄清楚如何按 zip 分组,然后添加一列显示同一城市每个 zip 的城市总人口。

[Ex Trying to find (Sum_of_City and Percent_of_City)] [前试图找到(Sum_of_City 和 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;

Use window functions:使用 window 函数:

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;

In case you're not on MySQL 8 (in which case you can't use Window Functions) , here's an alternative approach... Aggregate twice, then Join...如果您不在 MySQL 8 上(在这种情况下您不能使用 Window 函数) ,这是另一种方法......聚合两次,然后加入......

SELECT
  city_zip.city, city_zip.zip_code, city_zip.popluation, city_zip.poupluation / city.population AS ratio
FROM
(
    SELECT city, zipcode, sum(population) AS population
      FROM myTable
  GROUP BY city, zip_code
)
  AS city_zip
INNER JOIN
(
    SELECT city, sum(population) AS population
      FROM myTable
  GROUP BY city
)
  AS city
    ON city.city = city_zip.city

Or, using a correlated-subquery...或者,使用相关子查询...

SELECT
  city,
  zip_code,
  SUM(popluation),
  SUM(population)
  /
  (
    SELECT SUM(population)
      FROM myTable AS city
     WHERE city.city = city_zip.city
  )
FROM
  myTable AS city_zip
GROUP BY
  city,
  zip_code

I suspect the longer code might be faster, though I'm not entirely sure.我怀疑较长的代码可能会更快,但我不完全确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM