我在名为[Info]的ms访问中有下面提到的表。
AB JDE Quantity PO SMP
IND AB7049 15 F258738OD 10176
IND AM7619 21 F258738OD 10176
IND AS9147 20 F258738OD 10176
ARU AM7619 8 F118215OG 10176
ARU AM7619 16 F118215OG 10176
ARU AM7619 8 F118215OG 10176
ARU AM7619 12 F258210OD 10176
ARU AM7619 24 F258210OD 10176
ARU AM9147 120 F257894OD 10176
ARU AM9147 102 F257894OD 10176
ARU AS9147 18 F257905OD 10176
ARU AS9147 30 F257905OD 10176
这里我想进行如下表所示的连接和求和操作。
AB JDE Quantity PO SMP
IND AB7049, AM7619, AS9147 56 F258738OD 10176
ARU AM7619, AM9147, AS9147 338 F118215OG, F258210OD, F257894OD, F257905OD 10176
这里宏需要连接唯一的JDE和Unique PO,还需要总结与JDE和PO相关的qunatity。 SMP列是主键。
请在这个问题上帮助我。
答案 0 :(得分:0)
首先,SMP似乎不是主键。
我的方法是使用VBA函数来获取同心字符串,并在SQL中完成剩下的工作。
VBA功能:
Public Function getConcValues(ByVal pTablename As String, ByVal pFieldname As String, ByVal pSearchColumn As String, ByVal pSearchValue As String) As String
Dim rs As DAO.Recordset
Dim ret As String
Dim sql As String
' prepare SQL
sql = ""
sql = sql & "Select distinct [" & pFieldname & "] "
sql = sql & " From [" & pTablename & "] "
sql = sql & " Where [" & pSearchColumn & "] = '" & pSearchValue & "' "
sql = sql & "Order By [" & pFieldname & "]"
' initialize return value
ret = ""
' retrieve unique values based on search criterias
Set rs = CurrentDb.OpenRecordset(sql)
Do Until rs.EOF
' add content to return value
ret = ret & rs.Fields(0) & ", "
rs.MoveNext
Loop
' trim last comma if requiered
If Len(ret) > 0 Then
ret = Left(ret, Len(ret) - 2)
End If
' cleanup
rs.Close
Set rs = Nothing
' return result
getConcValues = ret
End Function
然后你可以在SQL中使用它:
SELECT
AB,
getConcValues("info","JDE","AB",[AB]) AS JDE,
Sum(Quantity) AS SumOfQuantity,
getConcValues("info","PO","AB",[AB]) AS PO,
SMP
FROM info
GROUP BY
AB,
getConcValues("info","JDE","AB",[AB]),
getConcValues("info","PO","AB",[AB]),
SMP;