I'm working with postgres
I have a table (tbl
) with the following fields: name, words
the fields type are strings)
I need to calculate for each name
(which is aaa
) the average percentage of words
which are not null
I have tried something like:
SELECT AVG(COUNT(words is not null) - count(*))
FROM tbl
WHERE name="test"
But I got the following error:
aggregate function calls cannot be nested
I tried to change the query to:
SELECT (AVG((SELECT COUNT(*) FROM tbl WHERE words IS NOT NULL) - (SELECT COUNT(*) FROM tbl))
FROM tbl
WHERE name="test"
but it seems that I got wrong values.
For example, for the following table:
name, words
----------------------------
test abc test, 1, 2, 3
t2 NULL
test NULL
t3 NULL
t2 a,b,c,d,e
test def zxy
t2 NULL
the result for test
need to be 2/3
(because there are 2 results of test
which are not null and there are 3 test
in the table)
How can I write the query in the right way ?
You cant nest it,
so go with subquery:
Output: