I new to postgresql and I am trying do calculate a rate in a table like this:
class phase
a sold
b stock
c idle
d sold
I want to calculate the total count of sold phases / total like this:
2/4 = 50%
i was trying:
with t as ( select count(class) as total_sold from table where phase='sold')
select total_sold / count(*) from t
group by total_sold
but the result is wrong. How can I do this?
Use
AVG()aggregate function:The boolean expression
phase = 'sold'is converted to an integer1fortrueor0forfalseand the average of these values is the ratio that you want.See the demo.