Lab schema (HR schema) is listed as below (primary keys are underlined):

Regions(region_id, region_name);
Countries(country_id, country_name, region_id);
Locations(location_id, street_address, postal_code, city, state_province, country_id);
Departments(department_id, department_name, manager_id, location_id);
Jobs(job_id, job_title, min_salary, max_salary);
Employees(employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, commission_pct, manager_id, department_id);
Job_History(employee_id, start_date, end_date, job_id, department_id);

Learning Objectives:

Write a single SQL query for each of the following questions.

  1. For each country, count the number of departments located in that country. List the name of the country and the count as numOfDepartments. If no department is there, the count should be shown as 0.
    select country_name, count(department_id) as numOfDepartments
    from   Departments natural join Locations X right join Countries C
           on X.country_id = C.country_id
    group by country_name;
    
    select country_name, count(department_id) as numOfDepartments
    from   Departments natural join Locations natural join Countries
    group by country_name
    union all
    select country_name, 0 as numOfDepartments
    from   Countries
    where  country_id not in (select country_id
                              from   Departments natural join Locations);
    
  2. List the name of each department that has more than 20 employees working in it.
    select department_name
    from   Departments D join Employees E on D.department_id = E.department_id
    group by department_name
    having count(employee_id) >= 20;
    
  3. For each department whose human resource cost (sum of salary of each employee in it) is greater than or equal to $40,000, list the department's name, the total salary and the average salary of the department.
    select department_name, sum(salary), avg(salary)
    from   Departments D join Employees E on D.department_id = E.department_id
    group by department_name
    having sum(salary) >= 40000;
    
  4. Find the department with the most people working in it. List the department's name.
  5. List the name of each employee who has more than 5 employees directly report to him/her.