Access Query多表,连接并删除重复项

时间:2013-07-28 05:07:18

标签: database multiple-columns

我附上了一个示例数据库,其中包含未完成的查询,我正在寻求帮助,图片显示了https://dl.dropboxusercontent.com/u/9829095/Result.jpg

示例数据库:https://dl.dropboxusercontent.com/u/9829095/Song-V2.accdb

1 个答案:

答案 0 :(得分:0)

Working solution from Duane Hookom
根据您的结构示例:

SELECT distinct ID
,Concatenate("SELECT distinct Genre FROM qrySong4Export WHERE ID =" & [ID]) as Genre
,Concatenate("SELECT distinct Artist FROM qrySong4Export WHERE ID =" & [ID]) as Artist
from qrySong4Export

输出:

ID  Genre   Artist
1   Genre 2, Genre 8    6, 12
2   Genre 9 1, 17
3   Genre 10, Genre 13  5
4   Genre 12    4, 5

代码(添加它创建 - >模块 - > [粘贴]):

Function Concatenate(pstrSQL As String, _
        Optional pstrDelim As String = ", ") _
        As String
'Created by Duane Hookom, 2003
'this code may be included in any application/mdb providing
'   this statement is left intact
'example
'tblFamily with FamID as numeric primary key
'tblFamMem with FamID, FirstName, DOB,...
'return a comma separated list of FirstNames
'for a FamID
' John, Mary, Susan
'in a Query
'SELECT FamID,
'Concatenate("SELECT FirstName FROM tblFamMem
' WHERE FamID =" & [FamID]) as FirstNames
'FROM tblFamily
'

'======For DAO uncomment next 4 lines=======
'====== comment out ADO below =======
    'Dim db As DAO.Database
    'Dim rs As DAO.Recordset
    'Set db = CurrentDb
    'Set rs = db.OpenRecordset(pstrSQL)

'======For ADO uncomment next two lines=====
'====== comment out DAO above ======
    Dim rs As New ADODB.Recordset
    rs.Open pstrSQL, CurrentProject.Connection, _
    adOpenKeyset, adLockOptimistic
    Dim strConcat As String 'build return string
    With rs
        If Not .EOF Then
            .MoveFirst
            Do While Not .EOF
                strConcat = strConcat & _
                .Fields(0) & pstrDelim
                .MoveNext
            Loop
        End If
        .Close
    End With
    Set rs = Nothing
'====== uncomment next line for DAO ========
    'Set db = Nothing
    If Len(strConcat) > 0 Then
        strConcat = Left(strConcat, _
        Len(strConcat) - Len(pstrDelim))
    End If
    Concatenate = strConcat
End Function