在Access中对连接的查找值进行分组

时间:2013-11-04 14:04:55

标签: sql ms-access select join group-by

我的数据库包含几个查找表(在UI表单中显示为下拉菜单)。

例如,

  

customer_data - 客户人口统计信息。

     

lookup_car - 存储汽车描述(Pinto,Vega,Reliant Robin,Mustang,Corvette)

     

junction_car_customer - 将客户与一辆或多辆汽车相结合

客户Jeremy Clarkson(cust_id:1)拥有三辆车。他的记录下拉列表显示:

Pinto (car_id=100)
Reliant Robin (car_id=101)
Vega (car_id=102)

junction_car_customer数据如下所示:

cust_id    car_id
1          100
1          101
1          102

我正在尝试返回显示客户名称和所拥有模型的行(作为分号分隔的字符串)。

这是我的疑问:

SELECT 
 cd.cust_id,
 cd.name_first,
 cd.name_last,
 jcc.car_id,
 lc.car_desc
FROM
 ((customer_data AS cd)
 LEFT JOIN ju_cust_car AS jcc ON jcc.cust_id = cd.cust_id)
 LEFT JOIN lookup_cars AS lc ON lc.car_id = jcc.car_id
ORDER BY 
 cd.name_last

返回:

cust_id name_first name_last car_id car_desc
1       Jeremy     Clarkson  100    Pinto
1       Jeremy     Clarkson  101    Reliant Robin
1       Jeremy     Clarkson  102    Vega 

我想要的是:

cust_id name_first name_last car_desc
1       Jeremy     Clarkson  Pinto;Reliant Robin;Vega

是否有一种有效的方法可以返回上述结果?

1 个答案:

答案 0 :(得分:1)

正如HansUp所说,您需要使用自定义VBA功能。如果数据是相当静态的,您可以通过缓存结果来加快速度。所以......

1)在VB编辑器中,添加对“Microsoft Scripting Runtime”的引用(我们将需要此库中的Dictionary类)。

2)创建一个新的标准模块,并向其添加代码,如下所示:

Option Explicit

Private mCache As New Scripting.Dictionary

Sub ClearCarDescCache(Optional cust_id)
  If IsMissing(cust_id) Then
    mCache.RemoveAll
  Else
    mCache.Remove CInt(cust_id)
  End If
End Sub

Function GetCarDescList(cust_id) As String
  If mCache.Exists(cust_id) Then
    GetCarDescList = mCache(cust_id)
    Exit Function
  End If
  Dim RS As DAO.Recordset, S As String
  Set RS = CurrentDb.OpenRecordset( _
    " SELECT car_desc " + _
    " FROM junction_car_customer INNER JOIN lookup_car " + _
    "   ON junction_car_customer.car_id = lookup_car.car_id " + _
    " WHERE cust_id = " & cust_id & _
    " ORDER BY car_desc", dbOpenForwardOnly)
  While Not RS.EOF
    If Len(S) = 0 Then
      S = RS(0)
    Else 
      S = S + ";" & RS(0)
    End If
    RS.MoveNext
  Wend
  mCache.Add cust_id, S
  GetCarDescList = S
End Function

3)主查询现在看起来像这样:

SELECT cust_id, name_first, name_last, GetCarDescList(cust_id) AS car_desc
FROM customer_data
ORDER BY name_last

4)根据需要向ClearCarDescCache添加显式调用。