Microsoft Access压缩表中的多行

Sam*_*m_H 18 ms-access

我在MS Access 2007中有一个问题,我希望有人有答案.我有一个很长但很简单的表,其中包含客户名称以及交付周的日期.我想通过将名称和所有日期列入一个新字段"ALLDays",同时仍然保留所有数据来总结此表.

源表看起来像这样:

Name         Day  
CustomerA    Monday  
CustomerA    Thursday  
CustomerB    Tuesday  
CustomerB    Friday  
CustomerC    Wednesday  
CustomerC    Saturday  
Run Code Online (Sandbox Code Playgroud)

我想有一个返回如下结果的查询:

Name         ALLDays  
CustomerA    Monday, Thursday  
CustomerB    Tuesday, Friday  
CustomerC    Wednesday, Saturday  
Run Code Online (Sandbox Code Playgroud)

谢谢.

Tho*_*mas 30

通常,您必须编写一个允许您创建连锁列表的函数.这是我用过的:

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
Run Code Online (Sandbox Code Playgroud)

Remou的版本具有附加功能,您可以传递值数组而不是SQL语句.


示例查询可能如下所示:

SELECT SourceTable.Name
    , GetList("Select Day From SourceTable As T1 Where T1.Name = """ & [SourceTable].[Name] & """","",", ") AS Expr1
FROM SourceTable
GROUP BY SourceTable.Name;
Run Code Online (Sandbox Code Playgroud)

  • +1。请注意在“ Dim oConn As ADODB.Connection”上出现错误“用户定义类型未定义”的读者:这是因为“首先需要设置对“ Microsoft ActiveX数据对象”(简称ADO)的引用。选择工具->引用从弹出的对话框中向下滚动,直到找到一个条目,该条目读取的内容类似于Microsoft ActiveX Data Objects 2.7 Library(选择您看到的最高编号),选中该条目旁边的复选框,然后单击“确定”。 ” 来源:http://p2p.wrox.com/excel-vba/39128-adodb-connection-user-defined-type-not-defined.html#post160935 (2认同)