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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With