Skip to content

2004. The Number of Seniors and Juniors to Join the Company 👍

 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
38
39
WITH
  AccumualtedCandidates AS (
    SELECT
      employee_id,
      experience,
      ROW_NUMBER() OVER(
        PARTITION BY experience
        ORDER BY salary, employee_id
      ) AS candidate_count,
      SUM(salary) OVER(
        PARTITION BY experience
        ORDER BY salary, employee_id
      ) AS accumulated_salary
    FROM Candidates
  ),
  MaxHiredSeniors AS (
    SELECT
      IFNULL(MAX(candidate_count), 0) AS accepted_candidates,
      IFNULL(MAX(accumulated_salary), 0) AS accumulated_salary
    FROM AccumualtedCandidates
    WHERE
      experience = 'Senior'
      AND accumulated_salary < 70000
  )
SELECT
  'Senior' AS experience,
  accepted_candidates
FROM MaxHiredSeniors
UNION ALL
SELECT
  'Junior' AS experience,
  COUNT(*) AS accepted_candidates
FROM AccumualtedCandidates AS Juniors
WHERE
  experience = 'Junior'
  AND Juniors.accumulated_salary < (
    SELECT 70000 - MaxHiredSeniors.accumulated_salary
    FROM MaxHiredSeniors
  );