Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 3 tables :-
Table 1 : a (applicant)
Id | Name | DOB
__________________
1 | xyz | 12/01/1990
2 | pqr | 06/02/1995

Table 2: b (Course)
Id | Course
____________
1 | Btech
2 | Mtech
3 | PhD

Table 3 : c
a_Id | b_Id | Year Completed
_______________________________
1 | 1 | 2008
1 | 3 | 2015
1 | 2 | 2012
2 | 2 | 2008
2 | 1 | 2006

I need to retrieve just the highest qualification of both the applicants using joins

Expected Result :
Name | Course | Year Completed
________________________________
xyz | PhD | 2015
pqr | Mtech | 2008

I'm using the below script :
SQL
select *
from a as t1
left outer join 
( select * from C where  Year in  (SELECT MAX(Year) Year FROM C GROUP BY a_Id )) as t2 on t1.Id = t2.a_Id
left outer join b as t3 on t2.b_Id = t3.Id


but I'm getting the following result

Actual Result:

Name | Course | Year Completed
________________________________
xyz |Mtech | 2012
pqr |Btech | 2006

Please help
Posted
Comments
Wombaticus 18-Aug-15 9:30am    
Why are you selecting MAX(year) if you want the highest qualification? I would have thought you'd want MAX(b_Id) in there somewhere.
scarletwitch1990 19-Aug-15 0:47am    
@Wombaticus : I do agree that, infact that was my first train of thoughts, but I figured that the Year of completion might be a good parameter to find out the higher qualification.

Well apart from the fact I get completely different results using the sql you have so far, Wombaticus has raised a perfectly valid point that you shouldn't assume that the higher qualification is gained after the lower qualification.

I would use something like
SQL
with CTE as (
    select Max(b_id) as Highest, a_Id
    from c group by a_Id
)
select a.[Name], b.Course, c.Year_Completed
from CTE
inner join a on a.Id = CTE.a_Id
inner join b on b.Id = CTE.Highest
inner join c on a.Id = c.a_Id and c.b_Id = b.Id

The Common Table Expression determines the highest qualification gained by each applicant. I can then use that to determine the name of the course and link to table c to find the year the applicant gained it. Table a is included only to get the name of the applicant.
 
Share this answer
 
Try this:
SQL
select a.name, b.course, c.year_completed
from a join c on a.id=c.a_id join b on b.id=c.b_id
where c.b_id = (select max(b_id) from c where c.a_id=a.id)
order by c.year_completed desc
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900