HackerRank-AdvancedJoin-Placements
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
Explanation See 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
My solution
SELECT my_name
FROM
(
SELECT f.id as friend_id,p.salary as f_salary
FROM STUDENTS s, FRIENDS f, packages p
WHERE s.id=f.id and f.friend_id = p.id
) f,
(
SELECT s.id,s.name as my_name, p.salary as my_salary
FROM STUDENTS s, packages p
WHERE s.id=p.id
) my
WHERE my.id=f.friend_id and my_salary < f_salary
ORDER BY f_salary ASC;
Most vote solution
select s.name
from students s, friends f, packages p, packages p2
where s.id = f.id and f.friend_id = p2.id and s.id = p.id and p.salary < p2.salary
order by p2.salary;
Comments