Return departmentid and the ratio males / females rounded to 2 decimals (mfratio). Use NULLIF so a zero-female…
SQLLevel: IntermediateConditional aggregation and pivots
Return department_id and the ratio males / females rounded to 2 decimals (mf_ratio). Use NULLIF so a zero-female department returns NULL instead of erroring.
Table definitions (from the source exercise):
CREATE TABLE employees(emp_id INTEGER PRIMARY KEY, name TEXT, department_id INTEGER, manager_id INTEGER, salary INTEGER, hire_date TEXT, job_title TEXT, gender TEXT);
Hints
- Distinguish a missing value from zero, an empty string and false.
- Test comparison, aggregation and filtering on a tiny missing-value example.
Answer
Approach: Divide the two conditional sums; wrap the denominator in NULLIF(x, 0).
SELECT department_id,
ROUND(1.0 * SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END)
/ NULLIF(SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END), 0), 2) AS mf_ratio
FROM employees
GROUP BY department_id;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT