简体   繁体   中英

SQL Server : compare two tables and return similar rows

I want to compare two tables, source and target, and get similar rows.

Compare source and target on Id one by one and:

  • If matched and it's two or more on Target => select All matched from Target
    • If matched and it's two or more on Source =>
    • for first matched if it doesn't selected before
      • select Matched From target
    • else (IF it have selected before)
      • check for next one matched

I think need a recursive expression to check source and target one by one

Source

x------x---------x
|  Id  |   Name  |
x------x---------x
|   1  |   a     |
|   2  |   b     |
|   2  |   c     |
|   3  |   d     |
|   3  |   e     |
|   4  |   x     |
x------x---------x

Target

x------x---------x
|  Id  |   Name  |
x------x---------x
|   1  |   f     |
|   1  |   g     |
|   2  |   h     |
|   3  |   i     |
|   3  |   j     |
|   5  |   y     |
x------x---------x

Result

x------x---------x
|  Id  |   Name  |
x------x---------x
|   1  |   f     |
|   1  |   g     |
|   2  |   h     |
|   3  |   i     |
|   3  |   j     |
x------x---------x

Test data

declare @s table(Id int, name varchar(20))
DECLARE @t table( Id int, name varchar(20))

INSERT @s values(1, 'a'), (2, 'b'), (2, 'c'), (3, 'd'), (3, 'e')

INSERT @t values(1, 'f'), (1, 'g'), (2, 'h'), (3, 'i'), (3, 'j')

I think you just need Exists operator to do this.

select * from @t t
where exists (select 1 from @s s where t.id=s.id)

SQLFIDDLE DEMO

SELECT DISTINCT 
    t.Id,
    t.name
FROM SOURCE s
INNER JOIN target t ON s.id=t.Id
WHERE s.Id IN (SELECT Id FROM target)

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