Skip to content
Quantoros

Return departmentid, headcount, and its percent of all employees rounded to 1 decimal (pct). Table definitions (from…

SQLLevel: IntermediateAggregation and HAVING

Return department_id, headcount, and its percent of all employees rounded to 1 decimal (pct).

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: Divide by a window SUM over the aggregate, or a scalar subquery COUNT.

SELECT department_id, COUNT(*) AS headcount,
       ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS pct
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