Placements

JOIN

Question Link

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

/*
Following query creates a table in the following format:
id | name | salary | friend_id | friend_name | friend_salary

The query then displays name of the students whose best friends got offered 
a higher salary than them. 
*/

SELECT
    tbl.name
FROM
    (SELECT
        b.*,
        p.salary AS friend_salary
    FROM
        (SELECT
            a.id,
            a.name,
            p.salary,
            a.friend_id,
            a.friend_name
        FROM
            (SELECT 
                t.*,
                s.name AS friend_name
            FROM students s
            JOIN 
                (SELECT 
                    s.id,
                    name,
                    friend_id
                FROM students s
                JOIN friends f USING (id)) t
            ON s.id = t.friend_id) a
        JOIN packages p USING(id)) b
    JOIN packages p ON b.friend_id=p.id) tbl
WHERE salary < friend_salary
ORDER BY friend_salary
 

-- OR

SELECT name
FROM
    (SELECT
        s1.*,
        f.friend_id,
        s2.name AS friend_name,
        p1.salary,
        p2.salary AS friend_salary
    FROM students s1
    JOIN friends f
    ON s1.id = f.id
    JOIN students s2
    ON f.friend_id = s2.id
    LEFT JOIN packages p1
    ON s1.id = p1.id
    LEFT JOIN packages p2
    ON f.friend_id=p2.id) AS t
WHERE friend_salary > salary
ORDER BY friend_salary

Last updated