简体   繁体   中英

Joining columns from different tables without duplicating

I have the table TableA with 100 rows in it. It has a column loanid , which may have duplicates.

I need to join with the other table TableB , which has a column loanid , to join with.

But, the loanid in tableB may or may not be in tableA .

So if I take a right join or left join , I want the result to be same as 100.

Since there is a matching and unmatching loanid in both table, there is a chance of result to be not 100 rows, if I do a right join or left join .

From what you describe you want a left join :

select . . .
from tablea a left join
     tableb b
     on a.loanid = b.loanid;

This keeps every row in tablea along with all matching rows in tableb . From your description, tableb doesn't have duplicates, so this will keep everything in tablea with no duplicates.

If tableb had duplicates and you wanted one arbitrary row, then you can use outer apply :

select . . .
from tablea a outer apply
     (select top 1 b.*
      from tableb b
      where a.loanid = b.loanid
     ) b;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM