Skip to content
Quantoros

Return departmentids where MORE than 50 percent of employees earn above 70,000. Table definitions (from the source…

SQLLevel: IntermediateAggregation and HAVING

Return department_ids where MORE than 50 percent of employees earn above 70,000.

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: AVG of a CASE (1/0) gives the share directly; compare in HAVING.

SELECT department_id
FROM employees
GROUP BY department_id
HAVING AVG(CASE WHEN salary > 70000 THEN 1.0 ELSE 0 END) > 0.5;

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