仅返回SQL Server的匹配行

时间:2017-08-06 06:33:47

标签: sql sql-server

我确信这很简单,但我真的被卡住了。以下是我想从两个具有相同结构的表中得到的结果集示例,在本例中是数据或记录

表A

 Ref  cola  colb id
 ------------------
 1     a      b   14
 1     a      b   24

表B

Ref  cola  colb id
------------------
 1     a      b  1
 1     a      b  2
 1     a      b  3

预期结果:

Ref  cola  colb id Ref1  cola1 colb1 id1
----------------------------------------
1      a     b   14  1      a      b   1
1      a     b   24  1      a      b   2

3 个答案:

答案 0 :(得分:2)

使用:

SELECT *
FROM table1 t1
JOIN Table2 t2
ON t1.Ref =t2.Ref AND t1.cola = t2.cola
   AND t1.colb = t2.colb AND t1.id = t2.id 

SELECT *
FROM table1 t1
JOIN Table2 t2
USING ( Ref , cola , colb, id )

答案 1 :(得分:1)

还有一种方式

;with cte
as
(
select Ref, cola,  colb, id,
hashbytes('sha1',concat(Ref, cola,  colb)) as tb1hash
from table1
)
 select 
 t1.Ref, --all required cols
 from cte c
join
(
select Ref, cola,  colb, id,
hashbytes('sha1',concat(Ref, cola,  colb)) as tb2hash
from table2
) b
on
b.tb2hash=c.tb1hash

答案 2 :(得分:0)

猜测:

;WITH TableAWithRowNum
AS (
SELECT *, ROW_NUMBER(ORDER BY id) AS RowNum
FROM dbo.TableA
), TableBWithRowNum
AS (
SELECT *, ROW_NUMBER(ORDER BY id) AS RowNum
FROM dbo.TableB
)
SELECT a.*, b.*
FROM TableAWithRowNum a 
INNER JOIN TableBWithRowNum b ON a.Ref = b.Ref 
--AND other join predicates on ColA, ... etc.
AND a.RowNum = b.RowNum