Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating percentage in PostgreSql

Tags:

sql

postgresql

I have a table like this for example:

string adm
A       2
A       1
B       2
A       1
C       1
A       2

And through a SQL query I want something like this:

string    perc_adm (%)
A            50
B            100
C            0

I want the percentage of number 2 occurrence in each string. I am able to get this in separate conditions but I need just one condition with it. Also I have some divided by zero error. How do I correct that in the condition?

like image 828
Bárbara Duarte Avatar asked Dec 22 '15 10:12

Bárbara Duarte


1 Answers

Try:

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

Here total::float convert the division into a float value, else int/int ==>int.

sql fiddle demo

like image 110
Praveen Avatar answered Sep 23 '22 01:09

Praveen