Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');sql
SELECT name, dept_id, salary,
ROUND(100.0 * salary / SUM(salary) OVER (PARTITION BY dept_id), 1) AS pct_of_dept
FROM employees WHERE dept_id IS NOT NULL
ORDER BY dept_id, salary DESC, name;| name | dept_id | salary | pct_of_dept |
|---|---|---|---|
| Asha | 1 | 120000 | 38.7 |
| Mei | 1 | 95000 | 30.6 |
| Ravi | 1 | 95000 | 30.6 |
| Tom | 2 | 70000 | 53.0 |
| Sara | 2 | 62000 | 47.0 |
| Diego | 3 | 55000 | 53.4 |
| Omar | 3 | 48000 | 46.6 |
Each department's percentages add up to about 100, allowing for rounding. Asha's 120000 of Engineering's 310000 is 38.7 percent.
Lena has no department and no salary, so she is excluded by the WHERE clause; otherwise her row would show NULL.
Rounded values may not sum to exactly 100.0. If a report must total 100, adjust the largest remainder or show one more decimal place.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
SELECT name, dept_id, salary,
ROUND(100.0 * salary / SUM(salary) OVER (PARTITION BY dept_id), 1) AS pct_of_dept
FROM employees WHERE dept_id IS NOT NULL
ORDER BY dept_id, salary DESC, name;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- SUM(x) OVER (PARTITION BY g) gives the group total per row
- Multiply by 100.0 to avoid integer division
- Rounded shares may not add up to exactly 100
- Exclude or label NULL rows
Common mistakes
- Integer division returning 0 for every share
- Using GROUP BY and losing individual rows
Follow-ups
- How would you show the share of the company total too?
- How would you handle rounding so shares add up to 100?
Tips
- Mention the rounding caveat