Question

I have a below result from the following query:

select 
count(CASE WHEN u.terms='A' AND u.space='R' THEN 1 END) as yes_count,
count(CASE WHEN u.terms='C' AND u.space='R' THEN 1 END) as no_count,
c.col1,c.col2
from schema1.table1 as u, schema1.table2 cu,schema1.table3 c
WHERE cu.created_date > now()- interval '5 days'
AND cu.tale2id=u.table2id
AND cu.oneid=c.oneid
Group by c.col2,c.col1;

Result

yes_count | no_count | col1 | col2
23444     |    456   | sdfd | 90
4444      |    456   |ghj   |34

Now I needed to write another query that will calculate the proportion of no_count provided. Below is the query I am trying to do the same:

select yes_count, no_count
     , count(no_count*100)/yes_count) as proportion of no_count
where col1 ='fgh' and col2= 34;

I am not able to pull this off correctly, is there anything wrong I am doing here?

Was it helpful?

Solution

query that will calculate the proportion of no_count provided.

SELECT *, no_count / (no_count + yes_count) AS no_count_ratio
FROM  (
   SELECT c.col1,c.col2
        , count(u.terms='A' AND u.space='R' OR NULL) AS yes_count
        , count(u.terms='C' AND u.space='R' OR NULL) AS no_count
   FROM   schema1.table1 u
   JOIN   schema1.table2 cu USING (tale2id)
   JOIN   schema1.table3 c  USING (oneid)
   WHERE  cu.created_date > now() - interval '5 days'
   GROUP  BY 1,2
   ) sub;
WHERE ....  -- to select specific rows ...

Assuming the total consists of "yes" and no" and no other options.
If you want "percentage" multiply by 100.
I put your main query into a subquery to make it easier, simplified the syntax a bit, but didn't change anything. Only added no_count_ratio to the outer query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top