如果BOTH表中存在数据,则获取结果

时间:2016-11-02 09:25:01

标签: sql excel-vba vba excel

我有一个用VBA(Excel)编写的SQL搜索,它可以工作并从表(test1)或表(test2)中找到测试数据

但是可以编写它以便只有当人员拥有BOTH表格中的数据时才会报告,即表格中的数据(test1) AND 表格(test2)

这是我当前的搜索仅作为OR:

Worksheets.ADD(After:=Worksheets(Worksheets.Count)).Name = "TEST"
Sheets("TEST").Select
Range("A1").Select

Dim TEST As String
    TEST = "SELECT DISTINCT s.master_id, s.eventdate, s.code " _
        & "FROM test1 s INNER JOIN person p ON s.master_id=p.entity_id AND p.audit=1 " _
        & "WHERE s.audit=1  " _
        & "UNION ALL SELECT DISTINCT h.master_id, h.eventdate, h.code " _
        & "FROM test2 h INNER JOIN person p ON h.master_id=p.entity_id AND p.audit=1 " _
        & "WHERE h.audit=1 " _
        & "ORDER BY master_id "

Set rs = conn.Execute(TEST)
With ActiveSheet.QueryTables.ADD(Connection:=rs, Destination:=Range("A1"))
    .Refresh
End With

rs.Close
Set rs = Nothing

3 个答案:

答案 0 :(得分:0)

可能会有所帮助

TEST = "SELECT DISTINCT s.master_id, s.eventdate, s.code " _
    & "FROM test1 s INNER JOIN person p ON s.master_id=p.entity_id AND p.audit=1 " _
    & "WHERE s.audit=1 and exists (select 1 from test2 h1 where s.master_id = h1.master_id) " _
    & "UNION ALL SELECT DISTINCT h.master_id, h.eventdate, h.code " _
    & "FROM test2 h INNER JOIN person p ON h.master_id=p.entity_id AND p.audit=1 " _
    & "WHERE h.audit=1 and exists (select 1 from test1 s1 where s1.master_id = h.master_id)" _
    & "ORDER BY master_id "

答案 1 :(得分:0)

用这个替换SQL:

SELECT P.entity_id, s.eventdate eventdate_1, s.code code_1, h.eventdate eventdate_2, h.code code_2
FROM PERSON P
     INNER JOIN TEST1 S ON S.master_id = P.entity_id AND S.audit = 1
     INNER JOIN TEST2 H ON H.master_id = P.entity_id AND H.audit = 1
WHERE P.audit = 1
ORDER BY P.entity_id

它显示两个表上的人员的Test1和Test2的数据。

答案 2 :(得分:0)

查看JOIN SYNTAX。

在您的情况下,INNER JOIN仅显示在BOTH Tables中具有COMMON DATA的人。 (相当于数学中的交集)