在PostgreSql中计算每个地区的城市人口总人口百分比

时间:2018-03-12 17:30:15

标签: sql postgresql

我有一张表,即3列和5437行的结算。 第一列有8组(A,B,C,D,E,F,G,H),第二列有' 6'组(城市,城镇,岛,郊区,哈姆雷特)

我的表格如下......

ID     district_name              Cluster         Population    

1003        A                    village            1543          
1002        B                    town               63437   
1003        C                    village            1698    
1002        D                    town               11785   
1040        E                    hamlet             100 
2034        F                    hamlet             190 
4003        G                    city               207561  
4243        H                    Suburb             682 
674         D                    Island             718 
1012        A                    village            1566
1040        F                    hamlet             200
1020        D                    town               11881
4055        D                    city               208763  

我想根据以下条件计算每个地区的人口百分比;

total population in each district/sum(population)*100
where cluster='city' or cluster='town'

感谢任何帮助 **我渴望的一个实际例子**

district_name Population_total(城市+城镇+岛屿)Urban_Percentage(Town_City)

     D                233147                      99.69(232429/233147 * 100)

1 个答案:

答案 0 :(得分:0)

<强> SQL DEMO

std::move

<强>输出

WITH  district as (         
     SELECT district_name, 
            sum("Population") as district_total
     FROM residentioal 
     where "Cluster"='city' or "Cluster"='town'
     GROUP BY district_name
), whole_total as (
     SELECT district_name, sum("Population") as total
     FROM residentioal 
     GROUP BY district_name
 )
SELECT d.district_name, 
       total as whole_total,
       district_total as city_town_total,        
       district_total * 100.0 / total as PP
FROM district d
JOIN whole_total  w
  ON d.district_name = w.district_name

修改

<强> SQL DEMO

您实际上只需一个查询即可:

| district_name | whole_total | city_town_total |                pp |
|---------------|-------------|-----------------|-------------------|
|             D |      233147 |          232429 | 99.69203978605772 |
|             B |       63437 |           63437 |               100 |
|             G |      207561 |          207561 |               100 |