这个需求,如果硬要用SQL来处理的话,我的解决方案是这样的:
1、代码:
- Sub SQL合并()
- Dim Ado As Object
- Dim conString As String
- Dim SQL1 As String, SQL2 As String, SQL3 As String, SQL As String
- Dim 数据库文件路径 As String
- 数据库文件路径 = ThisWorkbook.FullName
-
- If Application.Version >= 11 Then
- conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & 数据库文件路径 & ";Extended Properties=""Excel 12.0;HDR=YES"";"
- Else
- conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & 数据库文件路径 & ";Extended Properties=""Excel 8.0;HDR=YES"";"
- End If
- Set Ado = CreateObject("Adodb.Connection")
- Ado.Open conString
- If Ado.State = 1 Then
- Debug.Print "测试链接成功!"
- Else
- Debug.Print "测试链接失败!"
- End If
- SQL1 = "SELECT 年份,季节,店仓,款号,颜色,S,M,L ,XL ,XXL ,A,B ,FF" & _
- " FROM [源$A1:M] WHERE 年份 <> ''"
-
- SQL2 = "SELECT 年份,季节,店仓,款号,颜色,S,M,L ,XL ,XXL ,A,B ,FF" & _
- " FROM [源$N1:Z] WHERE 年份 <> ''"
-
- SQL3 = SQL1 & " UNION ALL " & SQL2
- SQL3 = "SELECT DISTINCT 年份,季节,店仓,款号,颜色 FROM (" & SQL3 & ")"
-
- SQL = "SELECT A.年份,A.季节,A.店仓,A.款号,A.颜色,B.S,B.M,B.L ,B.XL ,B.XXL ,B.A,B.B ,B.FF " & _
- "FROM (" & SQL3 & ") A " & _
- "LEFT JOIN (" & SQL1 & ") B " & _
- "On A.年份=b.年份 AND A.季节= B.季节 AND A.店仓=B.店仓 AND A.款号=B.款号 AND A.颜色=B.颜色"
-
- SQL = "SELECT A.年份,A.季节,A.店仓,A.款号,A.颜色,A.S,A.M,A.L ,A.XL ,A.XXL ,A.A,A.B ,A.FF,B.S,B.M,B.L ,B.XL ,B.XXL ,B.A,B.B ,B.FF " & _
- "FROM (" & SQL & ") A " & _
- "LEFT JOIN (" & SQL2 & ") B " & _
- "On A.年份=b.年份 AND A.季节= B.季节 AND A.店仓=B.店仓 AND A.款号=B.款号 AND A.颜色=B.颜色"
-
- With ThisWorkbook.Worksheets("模拟结果")
- .UsedRange.Offset(1).Clear
- .Range("A2").CopyFromRecordset Ado.Execute(SQL)
- End With
- Ado.Close
- End Sub
复制代码 2.注意事项:需要将数据源处理一下,
表头要统一,且删除没有用的字符,如 "T1." 和 "T2.";
统一格式,统计维度,即源里,标黄的部分要全部转换成文本格式,分列处理一下即可;
3.模拟结果如下:默认排序
4.附件在这里:
SQL合并.rar
(20 KB, 下载次数: 6)
最后,祝您生活愉快,推荐使用alipay
|