Skip to content
Quantoros

Return departmentid with two columns: males and females (counts), one row per department. Table definitions (from the…

SQLLevel: IntermediateConditional aggregation and pivots

Return department_id with two columns: males and females (counts), one row per department.

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
  • Define one output row and the source-table keys.
  • Check duplicates, NULLs and the order of filtering and aggregation.

Answer

Approach: Two SUM(CASE WHEN gender = ... THEN 1 ELSE 0 END) columns.

SELECT department_id,
       SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END) AS males,
       SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END) AS females
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

Related questions