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?
2
Answers
The correct syntax would be:
But you can (mis)use the
avg
function too:You are using perfectly valid syntax. It’s just incomplete, missing a
select
out front: demoThat makes your two parenthesized expressions uncorrelated scalar subqueries of the outer
select
. Note that you need the divident or the divisor to benumeric
,real
orfloat
to get a fraction, otherwise the result of dividing integers fromcount(*)
will be rounded.The proper (also quickest) way to do that is using aggregate
filter
clause:Picking
float
/double precision
overnumeric
, you won’t have to round off trailing zeroes.