Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

sql - Getting max value from rows and joining to another table

Sorry if this is being stupid, I am really a newbie trying to nail this.

Table A:
ID  Rank Name
1   100  Name1
1    45  Name2
2    60  Name3
2    42  Name4
2    88 Name5

Table B:
ID FileName
1  fn1
2  fn2

What I want is

1 fn1 name1
2 fn2 name5

This is what my query looks like, but it gives me multiple rows of results (instead of max) when i do the join

select B.Id B.FileName,A.Name
FRom B
JOIN ( 
select A.Id, MAX(A.Rank)as ExpertRank 
from A 
group by A.Id
) as NewA on A.Id = B.ID 
join B on A.Rank = NewA.Rank

Sub-query works fine, I get the problem on doing th join.

How do I fix this?

Thanks.

I have sql server 2008 R2

Last one is what I missed.

select B.Id B.FileName,A.Name 
FRom B 
JOIN (  
select A.Id, MAX(A.Rank)as ExpertRank  
from A  
group by A.Id 
) as NewA on A.Id = B.ID  
join B on A.Rank = NewA.Rank 
and A.Id = newA.Id
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...