-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataExpert-SQL45.sql
More file actions
37 lines (36 loc) · 823 Bytes
/
DataExpert-SQL45.sql
File metadata and controls
37 lines (36 loc) · 823 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
-- Question: Identify Department for Reduction
-- https://www.dataexpert.io/question/department-reduction-criteria
WITH less_than_5 AS (
SELECT
d.id AS dept_id,
d.name AS dep_name,
e.*,
SUM(salary) OVER (PARTITION BY d.id) AS total_salary,
COUNT(*) OVER (PARTITION BY d.id) AS emp_number
FROM
playground.dept d
LEFT JOIN
playground.emp e
ON d.id = e.department
),
odd_departments AS (
SELECT
*,
ROW_NUMBER() OVER (ORDER BY total_sal DESC, emp_count DESC, dept_id) AS seq
FROM
less_than_5
WHERE
emp_count <= 5
)
SELECT DISTINCT
dep_name,
emp_number,
total_salary
FROM
odd_departments
WHERE
seq % 2 = 1
ORDER BY
total_sal DESC,
emp_count DESC,
dep_name ASC;