根据公共ID组合来自多个记录的值

时间:2014-05-27 15:10:53

标签: ms-access ms-access-2013

我尝试了很多不同的方法来加入以下内容;

StockCode       Finished_Goods_Codes
100137           2105109
100137           2105110
100137           2105111

To;

StockCode        Finished_Goods_Codes
100137           2105109, 2105110, 2105111

我现行守则如下;

Public Function ListQuery()
 Dim curr As Database
    Dim rs As Recordset
    Dim SQLCmd As String
    Dim productList As String

    Set curr = CurrentDb()

    SQLCmd = "SELECT Finished_Goods_Codes FROM TEMP_codes WHERE [StockCode] = """ & StockCode & """"

    Set rs = curr.OpenRecordset(SQLCmd)

    If Not rs.EOF Then
        rs.MoveFirst
    End If

    Do While Not rs.EOF
        productList = productList & rs(0) & ", "
        rs.MoveNext
    Loop

    ListQuery = productList
End Function

我的查询目前运行以下内容;

SELECT TEMP_codes.StockCode, ListQuery([Products]) AS [List of Products]
FROM TEMP_codes
GROUP BY TEMP_codes.StockCode;

请你帮忙,因为我真的坚持这个。 非常感谢提前。

1 个答案:

答案 0 :(得分:1)

根据问题Microsoft Access condense multiple lines in a table给出的答案,以下是步骤:

1创建以下功能

Public Function GetList(SQL As String _
                            , Optional ColumnDelimeter As String = ", " _
                            , Optional RowDelimeter As String = vbCrLf) As String
'PURPOSE: to return a combined string from the passed query
'ARGS:
'   1. SQL is a valid Select statement
'   2. ColumnDelimiter is the character(s) that separate each column
'   3. RowDelimiter is the character(s) that separate each row
'RETURN VAL: Concatenated list
'DESIGN NOTES:
'EXAMPLE CALL: =GetList("Select Col1,Col2 From Table1 Where Table1.Key = " & OuterTable.Key)

Const PROCNAME = "GetList"
Const adClipString = 2
Dim oConn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim sResult As String

On Error GoTo ProcErr

Set oConn = CurrentProject.Connection
Set oRS = oConn.Execute(SQL)

sResult = oRS.GetString(adClipString, -1, ColumnDelimeter, RowDelimeter)

If Right(sResult, Len(RowDelimeter)) = RowDelimeter Then
    sResult = Mid$(sResult, 1, Len(sResult) - Len(RowDelimeter))
End If

GetList = sResult
oRS.Close
oConn.Close

CleanUp:
    Set oRS = Nothing
    Set oConn = Nothing

Exit Function
ProcErr:
    ' insert error handler
    Resume CleanUp

End Function

2为模块中的功能添加参考(工具 - >参考)。添加Reference Micorosft ActiveX Data Objects 6.1库(或最新的可用库)。

3使用与函数名称不同的名称保存模块,例如Concatenation

4运行以下查询

SELECT T.StockCode, GetList("Select Finished_Goods_Codes From TEMP_codes As T1 Where T1.StockCode = " & [T].[StockCode],"",", ") AS Finished_Goods_Codes
FROM TEMP_codes AS T
GROUP BY T.StockCode;