使用条件计算postgresql中的百分比

calculating percentage in postgresql with conditions

我有一个table,我想计算一列的百分比 我尝试以两种方式这样做。 但我实际上遇到了错误。

错误是'syntax error at or near "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

我的 table 有 5437 行,其中有 8 组 krs_name 而在另一列即 fclass 中,有 6 组。因此,我想为每个 krs_name 计算来自 fclass 的 4 个组的百分比。因此,我必须首先通过 krs_name 查询 count(fclass) 组,然后通过 krs_name 查询 fclass 等于我的条件组的 fclass 的计数,最后是 count(fclass) "with condition" / count(fclass) "total fclass" * 100 组 krs_name?

我正在使用 Postgresql 9.1。

问题出在这一行:

SELECT total.cluster, total.krs_name (

开括号没有意义。

但是,这似乎可以满足您的要求,而且简单得多:

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