【hackerrank】Placements
题目如下:
You are given three tables: Students, Friends and Packages. Students contains two columns: ID and Name. Friends contains two columns: ID and Friend_ID (ID of the ONLY best friend). Packages contains two columns: ID and Salary (offered salary in $ thousands per month).
Write a query to output the names of those students whose best friends got offered a higher salary than them. Names must be ordered by the salary amount offered to the best friends. It is guaranteed that no two students got same salary offer.
Sample Input
Sample Output
Samantha Julia Scarlet
ExplanationSee the following table:
Now,
- Samantha's best friend got offered a higher salary than her at 11.55
- Julia's best friend got offered a higher salary than her at 12.12
- Scarlet's best friend got offered a higher salary than her at 15.2
- Ashley's best friend did NOT get offered a higher salary than her
The name output, when ordered by the salary offered to their friends, will be:
- Samantha
- Julia
- Scarlet
解题思路:本题难度一般,涉及到三张表的联合。为了清晰易读,可以把Students和Packages做联合,查出每个学生的名字和工资,并记为结果集a;同时把Friends和Packages表做联合查询,查询每个朋友的工资,并记为结果集b;最后再对a和b做联合查询即可。
代码如下:
/* Enter your query here. */ select a.S_Name from (select s.Name as S_Name,s.ID as S_ID,p.salary as S_salary from Students s,Packages p where s.ID = p.ID) a, (select f.ID as F_ID,p.salary as F_salary from Friends f,Packages p where f.Friend_ID = p.ID) b where S_ID = F_ID and S_salary < F_salary order by F_salary;