【问题标题】:Convert numeric result to percentage with decimal digits将数字结果转换为带小数位数的百分比
【发布时间】:2016-01-17 04:44:44
【问题描述】:

我有这个问题:

Select count(incidentnumber) as average
from incidents
Where IncidentStationGround <> firstpumparriving_deployedfromstation;

我得到了一个结果,大概是 20,000。但是我怎样才能把这个数字转换成百分比呢?另外,我想要十进制的结果,可以吗?

【问题讨论】:

  • 这行得通吗? Select (count(incidentnumber)*100 /(select count(incidentnumber) from incidents)) as score from incidents Where IncidentStationGround &lt;&gt; firstpumparriving_deployedfromstation;

标签: sql postgresql casting aggregate-functions percentage


【解决方案1】:

假设占总数的百分比:

SELECT (count(incidentnumber) FILTER (WHERE IncidentStationGround <> firstpumparriving_deployedfromstation)
      * 100.0) / count(*) AS average
FROM   incidents;

将结果与numeric 常数相乘:100.0(带小数点!)将count() 的bigint 结果隐式转换为numeric。 (或显式转换。)

round() 是可选的。没有它你会得到很多小数位。

假设incidentnumber 定义为NOT NULL,那么count(*) 与count(incidentnumber) 的作用相同,只是快了一点。 (表定义将提供该信息。)

假设 Postgres 9.4 或更高版本。
相关答案与旧版本的链接和替代方案:

关于round()和numeric:

【讨论】:

    【解决方案2】:

    您在评论中的查询应该有效 将计数转换为小数以实现小数百分比

    count(incidentnumber)::decimal*100
    

    【讨论】:

    • 非常感谢,但是 :: 是什么意思?
    • :: 在 postgres 中转换运算符
    猜你喜欢
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    相关资源
    最近更新 更多