在 PostgreSql 中计算百分比

Bár*_*rte 9 sql postgresql

例如,我有一个这样的表:

string adm
A       2
A       1
B       2
A       1
C       1
A       2
Run Code Online (Sandbox Code Playgroud)

通过 SQL 查询,我想要这样的东西:

string    perc_adm (%)
A            50
B            100
C            0
Run Code Online (Sandbox Code Playgroud)

我想要每个字符串中第 2 次出现的百分比。我可以在不同的条件下获得它,但我只需要一个条件。我也有一些除以零错误。在这种情况下我该如何纠正?

Pra*_*een 16

尝试:

select 
    string,
    (cnt_2/total::float)*100 perc_adm
from (
    select 
        string, 
        count(*) total, 
        sum(case when adm = 2 then 1 else 0 end) cnt_2
    from tbl
    group by string
) x
order by string
Run Code Online (Sandbox Code Playgroud)

这里total::float将除法转换为float值, else int/int ==>int

sql小提琴演示

  • +1。考虑使用 [`nullif`](https://www.postgresql.org/docs/13/functions-conditional.html#FUNCTIONS-NULLIF) 来保护您的除法(以防 `count(*)` 返回任何行): `cnt_2 / nullif(总计, 0)::float` (8认同)