从行获取最大值并连接到另一个表

时间:2012-02-27 22:57:06

标签: sql sql-server sql-server-2008

对不起,如果这是愚蠢的,我真的是一个新手试图指出这一点。

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

我想要的是

1 fn1 name1
2 fn2 name5

这是我的查询的样子,但是当我进行连接时,它给了我多行结果(而不是max)

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

子查询工作正常,我在加入时遇到了问题。

我该如何解决这个问题?

感谢。

我有sql server 2008 R2

最后一个是我错过的。

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

3 个答案:

答案 0 :(得分:27)

你写的内容在from子句中缺少A,所以它不完全清楚你哪里出错但这应该有效

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

看到它正常工作here

或者你可以使用rownumber代替

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

看到它正常工作here

答案 1 :(得分:24)

以下是JOIN代替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

如果同一个ID没有重复的排名,则您不需要DISTINCT

答案 2 :(得分:0)

我个人喜欢以下内容。只是更干净的imo(尽管不确定性能)

select * 
from a
inner join b on a.id=b.id and b.rank=(select max(rank) rnk from b where id=id)