将表与标准相结合

时间:2017-06-09 14:22:20

标签: sql-server join

如何使用ID字段创建将TableA与TableB连接的MSSQL查询,但我希望它加入ID列中具有最高值的Number记录?

TableA  
ID  
1   
2   
3   
4   

TableB  
ID  Number
1   1
1   2
1   3
2   1
3   1
3   2
4   1
4   2
4   3

我希望这是我的输出

TableJoined
ID Number
1  3
2  1
3  2
4  3

有没有办法使用LEFT JOIN来实现这个目标或使用max()?

4 个答案:

答案 0 :(得分:3)

两者。在左连接上使用聚合。

Select t1.id, max(t2.number)
From table1 t1
Left join table2 t2 on t1.id= t2.id
Group by t1.id;

答案 1 :(得分:1)

您可以查询如下:

Select a.Id, Number from #a a join
(
    Select top(1) with ties * from #b 
    order by row_number() over(partition by id order by number desc) 
) b on a.id = b.id

答案 2 :(得分:0)

 Select A.Id, Max(Number) MaxNo from A 
 join B on A.Id=B.Id
 Group by A.Id

答案 3 :(得分:-1)

create table #a(
id int
)
go
create table #b(
id          int,
number      int  
)
go

insert into #a values(1),(2),(3),(4)

insert into #b values(1,1),(1,2),(1,3),(2,1),(3,1),(3,2),(4,1),(4,2),(4,3)


select #b.id,MAX(number) as maximum 
from #b left outer join #a on #b.id=#a.id
group by #b.id
相关问题