Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to calculate the fraction of rows fulfilling some criteria in Postgresql?

I would like to calculate the fraction of rows fulfilling some criteria. So something like this:

(SELECT COUNT(*) FROM table WHERE col_name > crit) / (SELECT COUNT(*) FROM table)

However, this creates a syntax error when I tried it.

How can I realize what I want?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The correct syntax would be:

select (select count(*)::decimal from table where col_name > crit) / count(*)::decimal
from table

But you can (mis)use the avg function too:

select avg(case when col_name > crit then 1.0 else 0.0 end)
from table
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading