• + 0 comments

    Query:

    WITH best_friend_salary as ( SELECT Students.id, name, salary as Person_Salary, Friend_id, (SELECT name FROM Students where id = friend_id) as Friend, (SELECT salary FROM Packages where id = friend_id) as Friend_Salary FROM Students JOIN Friends ON Students.id = friends.id JOIN Packages ON Students.id = Packages.id )

    SELECT name FROM best_friend_salary WHERE Person_Salary < Friend_Salary ORDER BY Friend_Salary;

    I have used CTE. A common table expression (CTE) is a named temporary result set that exists within the scope of a single statement and that can be referred to later within that statement, possibly multiple times.