首页 文章

用条件计算postgresql中的百分比

提问于
浏览
1

I have one table and I want to calculate the percentage of one column 我尝试过两种方式 . 但我实际上面对错误 .

错误是'语法错误处于或接近“select”'

这是我的代码如下:

WITH total AS 
(
    select krs_name,count(fclass) as cluster
    FROM residentioal
    GROUP BY krs_name
)
SELECT total.cluster, 
       total.krs_name
       (select count(fclass)
        FROM   residentioal
        where  fclass='village' 
        or     fclass='hamlet' 
        or     fclass='suburb' 
        or     fclass='island'
        AND    krs_name = total.krs_name
       )::float / count(fclass) * 100 as percentageofonline
 FROM  residentioal, total 
 WHERE residentioal.krs_name = total.krs_name
 GROUP BY total.krs_name total.krs_name

我的表有5437行,其中有8组krs_name,另一列是fclass,有6组 . 因此,我想计算每个krs_name的fclass中4组的百分比 . 因此,我必须首先通过krs_name查询count(fclass)组,然后查询fclass的计数,其中fclass等于我的条件组krs_name,最后count(fclass)“with condition”/ count(fclass)“total fclass “* 100 koup由krs_name?

我正在使用Postgresql 9.1 .

1 回答

  • 1

    问题出在这一行:

    SELECT total.cluster, total.krs_name (
    

    开放的paren毫无意义 .

    但是,这似乎做你想要的,它更简单:

    SELECT r.krs_name, COUNT(*) as total,
           AVG( (fclass in ('village', 'hamlet', 'suburb', 'island'))::int ) * 100 as percentageofonline
    FROM residentioal r 
    GROUP BY r.krs_name
    

相关问题