How can I calculate a ratio that express the proportionality grouped by another column?

Valerio Catalano :

Good Afternoon to everyone; I am questioned the following question : "List each class and its survival rate, i.e., the fraction of passengers in that class who survived. Try to round the number to the 2nd decimal digit."

The following is the code that I am using fro the query:

SELECT class, (100*count(survived)/total) as survival_rate
FROM Titanic
WHERE survived == 'yes'
GROUP BY class
HAVING total = (SELECT class, count(class) as total
FROM Titanic
GROUP  BY class)

The code is clearly not working but I cannot find a solution to the question that I am asked. Thank you very much for your precious help.

forpas :

You can group by class and round the average of the expression survived = 'yes':

select class, round(100.0 * avg(survived = 'yes'), 2) as survival_rate 
from Titanic 
group by class

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=368161&siteId=1