I am trying to retrieve the country with the second highest percentage of female workers from my dataset.
Theses are the dimensions that are relevant from the table:
Table name is "employee" country(varchar) male(boolean) female(boolean)
I am trying to retrieve the country with the second highest percentage of female workers from my dataset.
Theses are the dimensions that are relevant from the table:
Table name is "employee" country(varchar) male(boolean) female(boolean)
SELECT Country
FROM employee
GROUP BY Country -- get aggregate per Country
ORDER BY SUM(Female) / SUM(Male) DESC -- Higher percentage goes up
LIMIT 1, 1 -- after 1st, next 1 row(s)
;
It depends on the database. Assuming you're using MySQL (most used DB) boolean is an equivalent to tinyint(1). This makes integer arithmetics without casting or if then else logic possible:
SELECT country, (sum(male)/ sum(female)) as ratio FROM employee GROUP BY country order by ratio desc limit 2;
Then pick 2nd result (or use Limit 1, 1 if you're really not interested in the highest value).
If you need to cast as you're using PostGres you can have a look here: postgresql - sql - count of 'true' values