我有2个表(人,数据)。在数据表中,我需要搜索1个字段以获得不同的结果。
注意:我正在使用Excel VBA但是在SQL中编写此代码,因为我使用OLEDB从PostGreSQL数据库中提取数据
这是人员表格布局:
entity_id | dob
1 | 23/09/1951
3 | 08/11/1950
30 | 17/08/1959
61 | 03/06/1957
69 | 08/03/1941
72 | 03/03/1973
105 | 28/11/1925
108 | 08/10/1934
153 | 06/08/1939
168 | 11/03/1953
这是数据表布局
master_id | eventdate | code
1 | 11/11/2011 | 9Nu1.00
1 | 09/03/2016 | C10E700
3 | 16/11/1999 | 9Nu0.00
3 | 01/01/2008 | C10..00
30 | 27/11/2009 | C10F.00
61 | 18/02/2008 | 9Nu0.00
61 | 19/12/1997 | C10..00
69 | 01/05/1996 | 9Nu1.00
69 | 21/10/2004 | C10F.00
69 | 01/05/1995 | 9Nu0.00
72 | 09/03/2016 | 9Nu0.00
72 | 11/11/2011 | C10F.00
105 | 16/11/1999 | C10..00
108 | 18/10/2005 | C10F.00
153 | 19/12/1997 | 9Nu1.00
153 | 18/02/2008 | C10F.00
168 | 21/10/2004 | 9Nu0.00
168 | 01/05/1995 | C10F.00
我需要结果如下:
master_id | dob | a.eventdate | a.code | b.eventdate | b.code
1 | 23/09/1951 | 09/03/2016 | C10E700 | 11/11/2011 | 9Nu1.00
3 | 08/11/1950 | 01/01/2008 | C10..00 | 16/11/1999 | 9Nu0.00
30 | 17/08/1959 | 27/11/2009 | C10F.00 | 18/10/2005 |
61 | 03/06/1957 | 19/12/1997 | C10..00 | 18/02/2008 | 9Nu0.00
69 | 08/03/1941 | 21/10/2004 | C10F.00 | 01/05/1995 | 9Nu1.00
72 | 03/03/1973 | 11/11/2011 | C10F.00 | 09/03/2016 | 9Nu0.00
105 | 28/11/1925 | 16/11/1999 | C10..00 | 01/01/2008 |
108 | 08/10/1934 | 18/10/2005 | C10F.00 | 27/11/2009 |
153 | 06/08/1939 | 18/02/2008 | C10F.00 | 19/12/1997 | 9Nu1.00
168 | 11/03/1953 | 01/05/1995 | C10F.00 | 21/10/2004 | 9Nu0.00
这是我失败的代码
Sub GetData()
Const sqlconnection = "Provider=oledb;"
Dim conn As New Connection
conn.ConnectionString = sqlconnection
conn.Open
Dim rs As Recordset
Sheets("Sheet1").Select
Cells.Select
Selection.ClearContents
Range("A1").Select
Dim Q7 As String
Q7 = "SELECT a.master_id, p.dob, a.eventdate, a.code, b.eventdate, b.code " _
& "FROM data a WHERE a.code LIKE 'C10%' " _
& "JOIN people p ON p.entity_id=a.master_id " _
& "FROM data b WHERE ( b.code LIKE '9Nu0%' OR b.code LIKE '9Nu1%' ) " _
& "JOIN people p ON p.entity_id=b.master_id " _
& "ORDER BY a.master_id, a.eventdate DESC "
Set rs = conn.Execute(Q7)
With ActiveSheet.QueryTables.Add(Connection:=rs, Destination:=Range("A1"))
.Refresh
End With
rs.Close
End Sub
答案 0 :(得分:0)
请参阅此处的演示:http://rextester.com/QVXBLO35931
select a.master_id, p.dob, a.eventdate, a.code, max(b.eventdate), max(b.code)
from people p
join data a
on p.entity_id = a.master_id
and a.code like 'C10%'
left outer join data b
on p.entity_id = b.master_id
and b.code like '9Nu%'
group by a.master_id, p.dob, a.eventdate, a.code