SQL Server - Select first row that meets criteria

前端 未结 4 727
你的背包
你的背包 2021-01-29 06:18

I have 2 tables that contain IDs. There will be duplicate IDs in one of the tables and I only want to return one row for each matching ID in table B. For example:

Table

4条回答
  •  无人共我
    2021-01-29 06:46

    You can do so,by using a subselect for table a to get one entry per objectIdA group

    select b.*,a.[objectIdB]
    from b
    join 
    (select [objectIdA], max([objectIdB]) [objectIdB]
     from a group by [objectIdA]
    ) a 
    on(b.[objectIdA] = a.[objectIdA])
    

    Fiddle Demo

    Edit deom comments to get a whole row from tablea you can use a self join for tablea

    select b.*,a.*
    from b
    join a
      on(b.[objectIdA] = a.[objectIdA])
    join (select [objectIdA], max([objectIdB]) [objectIdB]
     from a group by [objectIdA]) a1 
      on(a.[objectIdA] = a1.[objectIdA] 
         and 
        a.[objectIdB] = a1.[objectIdB])
    

    Fiddle Demo 2

提交回复
热议问题