We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- SQL
- Advanced Join
- Placements
- Discussions
Placements
Placements
Sort by
recency
|
1746 Discussions
|
Please Login in order to post a comment
Extract the information
So we need to compare the the salary of Friends and Best Friends. Questions: 1. How to write a query to compare Salary? Solution: using self join on table that has Salary which is Packages 2. We need to compare Salary based on ID and Friend_ID, how to do this? Solution: we want to compare Salary therefore Salary is the main query.
Steps 1. Let's do a SELF JOIN to get Salary of students and best friends
Below is the completed query.
with CTE as (select Stds.ID,Stds.Name,Frnd.Friend_ID as Best_Friend_ID, Pk.Salary as Student_Salary, BFPk.Salary as Bestfriend_Salary from students Stds inner join Friends Frnd on Stds.ID = Frnd.ID inner join Packages PK on Pk.ID = Stds.ID inner join Packages BFPk on BFPk.ID = Frnd.Friend_ID), CTE_2 as ( select case When Bestfriend_Salary > Student_Salary Then Name end as bfmorethanstudent,Bestfriend_Salary from CTE) select bfmorethanstudent from CTE_2 where bfmorethanstudent is not null order by Bestfriend_Salary
SELECT std.Name as Friend
FROM Students as std INNER JONI Friends as friend ON std.ID = friend.ID INNER JOIN Packages ON std.ID = Packages.ID INNER JOIN Packages as pck ON friend.Friend_ID = pck.ID WHERE pck.Salary > Packages.Salary ORDER BY pck.Salary ASC
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.