【问题标题】:calculating percentage in postgresql with conditions用条件计算postgresql中的百分比
【发布时间】:2018-03-12 11:17:47
【问题描述】:

我有一张表,我想计算一列的百分比 我试图通过两种方式做到这一点。 但我实际上面临着错误。

错误是“选择”或附近的语法错误'

这是我在下面的代码:

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) 组,然后通过 krs_name 查询 fclass 的计数,其中 fclass 等于我的条件组,最后 count(fclass) "with condition" / count(fclass) "total fclass " * 100 组由 krs_name 组成?

我使用的是 Postgresql 9.1。

【问题讨论】:

  • 那里有语法错误,SELECT total.cluster, total.krs_name ( - 怀疑你想要在括号前的 total.krs_name 后面加逗号。
  • 一些示例数据和您的预期输出在这里真的会有很长的路要走。

标签: sql postgresql postgresql-9.1


【解决方案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

【讨论】:

  • 非常感谢亲爱的 Linoff 这正是我一直在寻找的解决方案。
猜你喜欢
  • 2017-05-13
  • 2020-10-20
  • 2013-10-27
  • 2018-07-22
  • 2023-02-11
  • 2010-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多