SQL JOIN主组到结果组

时间:2016-04-03 09:48:40

标签: sql excel postgresql excel-vba vba

我正在使用Excel VBA并使用OleDB连接到PGSQL。我有2行SQL代码可以在那里工作正常,但我现在需要合并它们。 第一个查询是主组,它找到第二个查询所需的人员

Const sqlconnection = "Provider=oledb;"

Dim conn As New Connection
conn.ConnectionString = sqlconnection
conn.Open
Dim rs As Recordset

Sheets("Sheet1").Select
Range("A1").Select

Dim GRP As String
GRP = "SELECT h.master_id, p.surname, p.forename1, h.eventdate, h.code " _
& "FROM hist h INNER JOIN person p ON h.master_id=p.entity_id " _
& "AND code LIKE 'C10%' " _
& "ORDER BY h.master_id "

第二个查询需要根据找到的第一组人员显示结果。

Dim DATA As String
DATA = "SELECT latest.master_id, p.surname, p.forename1, " _
& "SUBSTRING(latestAP,1,10) eventdate, " _
& "SUBSTRING(latestAP,12,3) TX1, " _
& "SUBSTRING(latestAP,16,3) TX2 " _
& "FROM ( " _
& "SELECT master_id, " _
& "MAX(CAST(eventdate AS VARCHAR(10)) + '.' + RIGHT('00' + TEXT1,3)+ '.' + RIGHT('00' + TEXT2,3)) as latestAP " _
& "FROM ap " _
& "GROUP BY master_id) AS latest " _
& "LEFT JOIN person p ON latest.master_id = p.entity_id " _
& "ORDER BY master_id "

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

rs.Close

1 个答案:

答案 0 :(得分:0)

考虑将第一个查询作为附加派生表添加到第二个查询:

Dim DATA As String 
DATA = "SELECT latest.master_id, p.surname, p.forename1, " _ 
     & "       SUBSTRING(latestAP,1,10) eventdate, " _ 
     & "       SUBSTRING(latestAP,12,3) TX1, " _ 
     & "       SUBSTRING(latestAP,16,3) TX2 " _ 
     & "FROM ( " _ 
     & "      SELECT master_id, " _ 
     & "             MAX(CAST(eventdate AS VARCHAR(10)) + '.' + " _
     & "                 RIGHT('00' + TEXT1,3) + '.' + " _
     & "                 RIGHT('00' + TEXT2,3)) as latestAP " _ 
     & "      FROM ap " _ 
     & "      GROUP BY master_id) AS latest " _ 
     & "INNER JOIN ( " _
     & "      SELECT h.master_id, p.surname, p.forename1, "_
     & "             h.eventdate, h.code " _ 
     & "      FROM hist h " _
     & "      INNER JOIN person p ON h.master_id=p.entity_id " _ 
     & "      AND code LIKE 'C10%') AS grp "
     & "ON grp.master_id = latest.master_id" 
     & "LEFT JOIN person p ON latest.master_id = p.entity_id " _ 
     & "ORDER BY master_id "