Getting max value from rows and joining to another table
What you wrote was missing A in the from clause so its not entirely clear where you went wrong but this should work
select
B.Id,
B.FileName,
A.Name
FRom B
INNER JOIN A
ON A.id = B.id
INNER JOIN (
select A.Id, MAX(A.Rank)as ExpertRank
from A
group by A.Id
) as NewA
ON a.Id = NewA.ID
AND a.Rank = NewA.ExpertRank
See it working here
Alternatively you could use rownumber instead
WITH CTE AS
(
SELECT ID,
RANK,
Name,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY RANK DESC) rn
FROM A
)
SELECT b.Id b.FileName,cte.Name
FROM
b
INNER JOIN cte
ON b.id = cte.id
and cte.rn = 1
See it working here
Here's an answer with JOINs instead of MAX():
SELECT DISTINCT b.id, b.filename, a1.name
FROM a a1
JOIN b
ON b.id = a1.id
LEFT JOIN a a2
ON a2.id = a1.id
AND a2.rank > a1.rank
WHERE a2.id IS NULL
If there are no duplicate ranks for the same id, then you don't need the DISTINCT
.
personally, i like the below. just cleaner imo (though not sure about performace)
select *
from a
inner join b on a.id=b.id and b.rank=(select max(rank) rnk from b where id=id)