在Microsoft Access 365中合并关联记录的SQL查询问题
在Access 365中合并同一品牌的成分到同一行的解决方案
一、先修正你的连接条件错误
你当前SQL的ON子句存在逻辑问题:tbl_main_new_registration.new_reg_id = tbl_supp_compositions.brand_name,这是用主表的ID去关联子表的品牌名称,不符合外键关联规则。正确的关联应该是主表的new_reg_id关联子表对应的外键字段(假设子表外键也是new_reg_id,如果不是请替换为实际字段名)。
二、创建自定义字符串聚合函数
Access没有内置的字符串合并聚合函数,我们需要自己写一个VBA函数来实现:
- 打开Access,按
Alt+F11打开VBA编辑器 - 点击菜单栏「插入」→「模块」,粘贴以下代码:
Function ConcatRelated(strField As String, _ strTable As String, _ Optional strWhere As String, _ Optional strOrderBy As String, _ Optional strSeparator As String = ", ") As Variant Dim rs As DAO.Recordset Dim strSql As String Dim strOut As String Dim varOut As Variant On Error GoTo Err_Handler '构建查询子表的SQL语句 strSql = "SELECT " & strField & " FROM " & strTable If Not IsMissing(strWhere) Then strSql = strSql & " WHERE " & strWhere End If If Not IsMissing(strOrderBy) Then strSql = strSql & " ORDER BY " & strOrderBy End If Set rs = CurrentDb.OpenRecordset(strSql) '遍历记录合并字段值 Do While Not rs.EOF If Not IsNull(rs(strField)) Then strOut = strOut & rs(strField) & strSeparator End If rs.MoveNext Loop rs.Close '移除末尾多余的分隔符 If Len(strOut) > 0 Then strOut = Left(strOut, Len(strOut) - Len(strSeparator)) End If '返回合并结果(空值则返回Null) If strOut = "" Then varOut = Null Else varOut = strOut End If ConcatRelated = varOut Exit_Handler: Set rs = Nothing Exit Function Err_Handler: MsgBox "错误: " & Err.Description, vbExclamation ConcatRelated = Null Resume Exit_Handler End Function
- 保存模块,注意模块名称不能是
ConcatRelated,可以命名为modStringAggregator之类的。
三、编写最终查询SQL
使用上面的自定义函数,将同一品牌的所有成分和含量合并到一行:
SELECT tbl_main_new_registration.brand_name, ConcatRelated("active_ingredient", "tbl_supp_compositions", "new_reg_id = " & tbl_main_new_registration.new_reg_id) AS 所有活性成分, ConcatRelated("strength", "tbl_supp_compositions", "new_reg_id = " & tbl_main_new_registration.new_reg_id, "active_ingredient") AS 对应含量 FROM tbl_main_new_registration GROUP BY tbl_main_new_registration.brand_name, tbl_main_new_registration.new_reg_id;
关键说明
- 如果你的
new_reg_id是文本类型,关联条件需要加单引号:"new_reg_id = '" & tbl_main_new_registration.new_reg_id & "'" ConcatRelated的第5个参数可以自定义分隔符,比如改成"; "或者"<br>"(报表/表单中用)GROUP BY必须包含主表的唯一标识new_reg_id,避免同一品牌不同ID的记录被错误合并
内容的提问来源于stack exchange,提问作者AgileMethod
相关产品推荐
相关产品推荐

