MS Access:将查询结果转换为带分隔符的字符串
Posted
技术标签:
【中文标题】MS Access:将查询结果转换为带分隔符的字符串【英文标题】:MS Access: convert query results to string with delimiter 【发布时间】:2014-07-16 12:13:54 【问题描述】:我需要将查询结果作为带分隔符的字符串来查看。
例子:
表格“汽车”
carId | carName
1 | Honda
2 | Ford
表“驱动程序”
driverId | driverName
1 | John
表“时间表”
tDate | tDriver | tCar
15/07/2014 | 1 | 1
15/07/2014 | 1 | 2
查询“二手车”
driver | car
1 | 1
1 | 2
我需要查询“UsedCars”中的结果如下所示:
driver | car
1 | 1;2
任何帮助将不胜感激。
【问题讨论】:
谢谢大家。在这里找到工作解决方案:***.com/questions/17350055/… 【参考方案1】:这就像 mysql 中的 GROUP CONCAT
,在 MS Access 中不可用。但是有一种解决方法,例如,您可以在 MS Access 中创建一个名为 GetList
的函数(通过模块),这样您就会有以下查询:
SELECT Driver, GetList("SELECT Car FROM UsedCars","",";") as Cars
FROM UsedCars
GROUP BY Driver
使用VBA
的函数如下:
Option Compare Database
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
来源here
【讨论】:
【参考方案2】:你试过串联吗?
http://www.techonthenet.com/access/functions/string/concat.php
【讨论】:
OP 不仅在寻找连接,还寻找GROUP BY
其分组值被连接。
也许你是对的,我的第一个答案是不对的,但是 group by 不会解决这个问题。在 postgresql 中会需要类似 string_agg() 函数的东西...
尝试搜索:ms+access+convert+array+to+string
其实这个对我有用:***.com/questions/17350055/…以上是关于MS Access:将查询结果转换为带分隔符的字符串的主要内容,如果未能解决你的问题,请参考以下文章
解决mysql查询,in条件参数为带逗号的字符串,查询结果错误