实例 16 :替代 VLOOUP、SUMPRODUCT 的VBA编码-多重 Join 的使用 http://club.excelhome.net/viewthread.php?tid=183367&px=0 Sub findd() Dim SQL$ Set CNN = CreateObject("ADODB.Connection") CNN.Open "provider=microsoft.jet.oledb.4.0;extended properties='Excel 8.0;imex=1';data source=" & ThisWorkbook.FullName For i = 2 To [IV1].End(xlToLeft).Column sql1 = sql1 & "数量" & i & "," sql2 = sql2 & "(" sql3 = sql3 & " left join (select 时间,数量 as 数量" & i & " from [sheet3$] where id=" & Sheet2.[a:a].Find(Cells(1, i), LookIn:=xlValues, LookAt:=xlWhole).Offset(0, 1) & ") as b" & i & " on a.时间=b" & i & ".时间)" Next sql1 = Left(sql1, Len(sql1) - 1) SQL = "select " & sql1 & " from (" & sql2 & "select 时间 from [sheet1$]) as a " & sql3 'MsgBox SQL [B2].CopyFromRecordset CNN.Execute(SQL) CNN.Close Set CNN = Nothing End Sub 循环后形成的查询字符串 SQL 为: select 数量2,数量3,数量4,数量5 from (((((select 时间 from [sheet1$]) as a left join (select 时间,数量 as 数量2 from [sheet3$] where id=712) as b2 on a.时间=b2.时间) left join (select 时间,数量 as 数量3 from [sheet3$] where id=713) as b3 on a.时间=b3.时间) left join (select 时间,数量 as 数量4 from [sheet3$] where id=714) as b4 on a.时间=b4.时间) left join (select 时间,数量 as 数量5 from [sheet3$] where id=715) as b5 on a.时间=b5.时间) 用 left join 对12个月同时汇总: http://club.excelhome.net/viewthread.php?tid=208147&replyID=641892&skin=0 http://club.excelhome.net/dispbbs.asp?boardid=2&replyid=169351&id=128977&page=1&skin=0&Star=4 left join 的另三个例子及解释: http://club.excelhome.net/viewthread.php?tid=211784&extra=&page=1#211784 http://club.excelhome.net/dispbbs.asp?boardid=2&replyid=633116&id=205934&page=1&skin=0&Star=3 http://club.excelhome.net/viewthread.php?tid=218216&replyID=705633&skin=1 left join 的括号配对: http://club.excelhome.net/viewthread.php?tid=211186&extra=&page=2#661249 从语法上来看,LEFT JOIN 只允许一层,也即: SELECT 字段 FROM 基准表 LEFT JOIN 后续表 ON 基准表.同型字段=后续表.同型字段 而不能在后面直接继续其它的 LEFT JOIN : SELECT 字段 FROM 基准表 LEFT JOIN 后续表 ON 基准表.同型字段=后续表.同型字段 LEFT JOIN ................ 但如果我们加上括号,就可以把第一层 LEFT JOIN 变成“新基准表”,而在此“新基准表”后面就可以连接 LEFT JOIN 了: SELECT 字段 FROM (基准表 LEFT JOIN 后续表 ON 基准表.同型字段=后续表.同型字段) LEFT JOIN 后续表2 ON 基准表.同型字段=后续表2.同型字段 ↑ 新基准表 所以使用括号,就可以连接多个 LEFT JOIN ,只要保证括号配对,从整体上看只有一个基准表、一个 LEFT JOIN、一个后续表、一个ON即可。
[此贴子已经被作者于2007-2-1 22:26:51编辑过] |