访问sql查询以连接行

时间:2011-12-22 09:15:13

标签: sql ms-access

我有csv格式的以下数据,我以访问格式

导出
House Number | Road name | Postcode
1 | alex road | sw2 4r
2 | alex road | sw2 4r
3 | alex road | sw1 2b
4 | alex road | sw2 4r
5 | alex road | sw2 4r
7 | brit road | bw2 4t
4 | brit road | bw2 4t
6 | brit road | bw2 4t
8 | brit road | bw2 4t
10 | brit road | bw2 4t

我需要一个ACCESS SQL查询,它可以按路名分组所有记录,总记录可以超过20,000

我需要以下格式输出

Road Name | House Number | Postcode
--------------------------------------
alex road | 1,2,3,4,5 |  sw2 4r,sw1 2b
brit road | 7,4,6,8,10 | bw2 4t

2 个答案:

答案 0 :(得分:1)

正如oneday在SO早期的帖子中指出的那样,使用ADO会更容易,有an example here

示例查询:

   SELECT d.DeptID, d.Department, 
          ConcatADO("SELECT FName & ' ' & SName, Address FROM Persons 
                     WHERE DeptID=" & [d].[DeptID],", "," : ") AS Who
   FROM Departments AS d INNER JOIN Persons AS p ON d.DeptID = p.DeptID
   GROUP BY d.DeptID, d.Department, 3;

使用ADO的功能

Function ConcatADO(strSQL As String, strColDelim, strRowDelim, ParamArray NameList() As Variant)
   Dim rs As New ADODB.Recordset
   Dim strList As String

   On Error GoTo Proc_Err

       If strSQL <> "" Then
           rs.Open strSQL, CurrentProject.Connection
           strList = rs.GetString(, , strColDelim, strRowDelim)
           strList = Mid(strList, 1, Len(strList) - Len(strRowDelim))
       Else
           strList = Join(NameList, strColDelim)
       End If

       ConcatADO = strList

   Exit Function

   Proc_Err:
       ConcatADO = "***" & UCase(Err.Description)
   End Function

答案 1 :(得分:0)

因为在Access中没有像group_concat这样的函数。所以我使用其内置的导入工具将我的csv文件导入phpMyAdmin mysql数据库,并使用以下查询对它们进行分组

SELECT  road,pcode, group_concat(house_number) 
FROM mytable
GROUP BY road, pcode

然后使用内置导出工具中的phpmyadmin将其导出回csv。我不知道是否有更好的方法。