我有两张表(1& 2)应该合并为第三张(3)。
表1:F_Number,A_Number,A_Weight
表2:A_Number,A_Country
表3:F_Number,A_Country,A_Weight
thrid表应按F_Number进行分组,总结A_Weight,其中A_Country具有相同的值。到目前为止,表的连接工作正常:
Dim strSQL As String
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String
Dim sconnect As String
DBPath = ThisWorkbook.FullName
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
Conn.Open sconnect
strSQL = "Select [Table1$].[F_Number], [Table2$].[A_Country], [Table1$].[A_Weight] From [Table1$] Inner Join [Table2$] On [Table2$].[A_Number]=[Table1$].[A_Number]"
mrs.Open strSQL, Conn
ActiveSheet.Range("A2").CopyFromRecordset mrs
mrs.Close
Conn.Close
结果是这样的表:
F_Number;一个国家; A_Weight
F_1;我们; 10%
F_1:美国; 10%
F_1;英国; 80%
F_2;英国; 100%
我希望这个表按" A_Weight"分组。像这样:
F_Number;一个国家; A_Weight
F_1;我们; 20%
F_1;英国; 80%
F_2;英国; 100%
我对SQL知之甚少,但到目前为止我尝试的是总结A_Weight并将结果按F_Number分组,这给了我一条错误信息。我使用的是德语办公室版本,因此我只能尝试翻译错误:"自动化错误"。我仍然认为它应该是这样的。
以下是我的非工作 SQL-String代码:
strSQL = "Select [Table1$].[F_Number], [Table2$].[A_Country], Sum([Table1$].[A_Weight]) From [Table1$] Inner Join [Table2$] On [Table2$].[A_Number]=[Table1$].[A_Number] Group By [Table1$].[F_Number]"
答案 0 :(得分:2)
你的代码很好;你只需要修改SQL查询。
strSQL = "SELECT [Table1$].[F_Number], [Table2$].[A_Country], SUM([Table1$].[A_Weight]) " & _
"FROM [Table1$], [Table2$] " & _
"WHERE [Table2$].[A_Number] = [Table1$].[A_Number] " & _
"GROUP BY [Table1$].[F_Number], [Table2$].[A_Country]"