SQL JOIN:匹配时从LEFT和RIGHT表返回行

时间:2017-10-04 19:42:53

标签: sql sql-server

我有一个#tmp表,我需要找到LEFT表和RIGHT表中具有匹配的Name和Coverage的所有记录。

-- select * from #tmp
--#tmp table
ID  Name  IsConverted  Coverage  EarliestPolicyEffectiveDate
1   abc   1            Test1     9/1/2017
2   abc   0            Test1     9/2/2017
3   abc   0            Auto      9/3/2017
4   xyz   0            Home      9/3/2017

-- select * from #tmp where IsConverted = 0
--LEFT TABLE
ID  Name  IsConverted  Coverage
2   abc   0            Test1
3   abc   0            Auto
4   xyz   0            Home

-- select * from #tmp where IsConverted = 1
--RIGHT TABLE
ID  Name  IsConverted  Coverage
1   abc   1            Test1

-- DESIRED RESULTS
ID  Name  IsConverted  Coverage
1   abc   1            Test1
2   abc   0            Test1

-- CURRENT RESULTS
ID  Name  IsConverted  Coverage
2   abc   0            Test1



select *
from 
    (SELECT * FROM #tmp tmp WHERE tmp.IsConverted = 0) nc
join
    (SELECT * FROM #tmp tmp WHERE tmp.IsConverted = 1) ic on ic.Name = nc.Name and ic.Coverage = nc.Coverage

我需要能够从左右两个表中获取匹配的记录。原因很复杂,并没有为这篇文章添加任何其他信息。

我尝试过FULL OUTER JOIN,CROSS APPLY,OUTER APPLY。没有什么工作。

编辑:

最好我想使用JOIN,因为一旦找到匹配的结果,我仍然需要访问左表和右表,因为我需要在RIGHT.EarliestPolicyEffectiveDate的15天内确保LEFT.EarliestPolicyEffectiveDate。

如果我做UNION ALL,我不确定我能做到。

如下例所示:

select *
from 
    (SELECT * FROM #tmp tmp WHERE tmp.IsConverted = 0) nc
join
    (SELECT * FROM #tmp tmp WHERE tmp.IsConverted = 1) ic on ic.Name = nc.Name and ic.Coverage = nc.Coverage
where 
    nc.EarliestPolicyEffectiveDate between DATEADD(d, -15, ic.EarliestPolicyEffectiveDate) and DATEADD(d, 15, ic.EarliestPolicyEffectiveDate)

3 个答案:

答案 0 :(得分:3)

我认为有更好的方法可以做到这一点,但UNION ALLEXISTS似乎在这里工作:

SELECT *
FROM #tmp t
WHERE IsConverted = 1 
AND EXISTS(SELECT 1 FROM #tmp
           WHERE IsConverted = 0
           AND Name = t.Name
           AND Coverage = t.Coverage)
UNION ALL
SELECT *
FROM #tmp t
WHERE IsConverted = 0
AND EXISTS(SELECT 1 FROM #tmp
           WHERE IsConverted = 1
           AND Name = t.Name
           AND Coverage = t.Coverage);

答案 1 :(得分:1)

这对我有用。有一个子查询来获取LEFT和RIGHT之间的所有匹配名称。和一个子查询,以获得左和右之间的所有匹配覆盖。然后使用' AND'在WHERE子句

中将它们链接在一起
select * from #tmp
where name in (Select LEF.Name from LEF 
                INNER JOIN RIG ON LEF.NAME = RIG.NAME) 
        and coverage in (Select LEF.coverage from LEF 
                INNER JOIN RIG ON LEF.coverage = RIG.coverage)

结果:

ID          NAME       IsConverted Coverage   EarliestPolicyEffectiveDate
----------- ---------- ----------- ---------- ---------------------------
1           abc        1           Test1      2017-09-01
2           abc        0           Test1      2017-09-02

答案 2 :(得分:0)

我想我现在看到你试图将LEFT TABLE直接加入到RIGHT TABLE中,而不是使用#tmp作为中间连接。

你需要将两个相交的地方联合起来。

伪码:

SELECT * FROM LEFT TABLE WHERE EXISTS(matching row in RIGHT TABLE)
UNION 
SELECT * FROM RIGHT TABLE WHERE EXISTS(matching row in LEFT TABLE)