ITPEC FE Morning October 2020 Question 26

Topic: Databases

The employee’s ID, name, salary, manager ID, and working department are recorded in the Employees table as follows:

Employees

Emp_IDEmp_nameSalaryManager_IDDID
10Amit50000183
11Vikrom75000162
12Nishi40000183
13Niloy60000171
14Pritom80000183
15Mohitlal45000183
16Rahman90000null1
17Roxy55000162
18Santosh65000171

When a query is formulated in SQL to retrieve the manager ID and the average salary of the employees under his/her direct report, and the output is obtained as below, which of the following is the appropriate combination to be inserted in blanks E and F in the SQL statement?

select E as "Manager_ID",
avg(a.Salary) as "Average_Salary"
from Employees a, Employees b
where E = F
group by E
order by E
Manager_IDAverage Salary
1665000
1762500
1853750
OptionEF

Explanation

E: b.Emp_ID, F: a.Manager_ID — join each employee (a) to the row of his or her manager (b), then group by the manager.

The condition b.Emp_ID = a.Manager_ID pairs every employee row a with the row b of the person he or she reports to. Grouping by b.Emp_ID makes one group per manager, and avg(a.Salary) averages the salaries of that manager's direct reports. Rahman, whose Manager_ID is null, matches no b row and drops out.

ManagerDirect reportsAverage
16Vikrom 75000, Roxy 5500065000
17Niloy 60000, Santosh 6500062500
18Amit 50000, Nishi 40000, Pritom 80000, Mohitlal 4500053750

This matches the output.

Answer (d)

Why not others:

  • •(a) — joining and grouping on DID averages by department, so the first column would show department IDs 1, 2 and 3, not manager IDs
  • •(b) — joining on Emp_ID pairs each row with itself, giving nine groups of one employee with his or her own salary
  • •(c) — pairs each employee with every colleague who has the same manager; each salary is counted once per colleague, so the averages happen to come out the same for this data, but the join never reaches the manager's own row and multiplies rows for nothing, so it is not the manager–subordinate join the query describes

Key rule: In a self-join, give each alias one role, here a for the subordinate and b for the manager, and join the subordinate's foreign key to the manager's primary key.

Databases · AI-written, may contain errors

This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.