【发布时间】:2014-04-10 07:24:42
【问题描述】:
我在 Access 2007 中有下表:
Route Cust Planners
4401 1004 jasper
4401 1005 onno
4401 1006 jasper
4402 1007 bart
4402 1008 marcel
4402 1059 onno
4403 1124 bart
4403 1165 marcel
4403 1198 marcel
4403 1201 mustafa
4403 1225 bart
4401 1178 maurice
我想要这个结果(所有客户和所有规划者一起拥有相同的路线):
Route Cust Planners
4401 1004;1006;1178;1005 jasper;maurice;onno
4402 1007;1008;1059 bart;marcel;onno
4403 1124;1225;1165;1198;1201 mustafa;marcel;bart
这可能是通过查询还是仅通过 VBA 代码? 提前致谢!
编辑@Dan(已解决): 感谢您的步骤,我有做这样的事情的想法,但不知道具体如何。 在对我有用的代码下方(它可能更容易完成,代码更少,但它可以完成工作)
Dim rs As DAO.Recordset
Dim cust, planners As String
Dim route, route2, cntr As Integer
DoCmd.RunSQL "Delete * FROM details2"
Set rs = CurrentDb.OpenRecordset("select * from details order by route, cust")
rs.MoveFirst
cntr = 0
Do While Not rs.EOF
route = rs.Fields("Route")
'If route readed from recordset is not the same as local variable then insert that route and give local variable the new route and clear cust and planners
If route <> route2 Then
'If going through loop for first time => do no insert
If cntr > 0 Then
'Delete last comma for both cust and planners field and insert that route
cust = Left(cust, Len(cust) - 1)
planners = Left(planners, Len(planners) - 1)
DoCmd.RunSQL "insert into details2 (Route, Cust, Planners) Values (" & route2 & ", '" & cust & "', '" & planners & "')"
End If
route2 = route
cust = ""
planners = ""
End If
'If route readed is the same as local variable, add cust and planner to the string but only if it isn't in the string already
If route = route2 Then
If InStr(cust, CStr(rs.Fields("cust"))) = 0 Then cust = cust + CStr(rs.Fields("cust")) & ","
If InStr(planners, rs.Fields("planners")) = 0 Then planners = planners + rs.Fields("planners") & ","
End If
rs.MoveNext
cntr = cntr + 1
Loop
'Delete last comma for cust and planners field and add last route
cust = Left(cust, Len(cust) - 1)
planners = Left(planners, Len(planners) - 1)
DoCmd.RunSQL "insert into details2 (Route, Cust, Planners) Values (" & route2 & ", '" & cust & "', '" & planners & "')"
这给了我以下结果:
Route Cust Planners
4401 1004,1005,1006,1178 jasper,onno,maurice
4402 1007,1008,1059 bart,marcel,onno
4403 1124,1165,1198,1201,1225 bart,marcel,mustafa
非常感谢!
【问题讨论】:
-
我怀疑你真的想要用分号分隔的值列表;您不能使用简单的“从任何 ORDER BY Route 中选择 Route、Cust、Planners”,每个 Route 的所有数据都在连续的行中,然后一次处理一行,将单独的 Cust 和 Planners 值收集到适当的数据中结构没有繁琐的解析?
-
@LorenzoGatti:如果结果用于报告输出怎么办?在这种情况下,将字符串连接到组上是非常有意义的,这样可以让最终用户对给定路线的 Cust 和 Planner 有一个快速而紧凑的概览。
-
@LorenzoGatti:嗯,它不一定是分号,可以是逗号。但是如何在查询中一次处理一行?
-
@Dan:是的,没错。只是为了更快地查看特定路线的客户和计划者