1

我搜索了“连接”主题,但无法找到我需要的答案。这篇文章接近 访问 sql 查询以连接行,但我试图让它为我的目的工作失败了。

我有一张这样的桌子

Lic# | Permit  | Year     
------------------------
1    | NS1     |   2003   
1    | NS1     |   2004  
1    | NS2     |   2004  
2    | TR      |   2012  
2    | NS2     |   2012  
3    | OR      |   2008   
2    | OR      |   2011  
2    | NS1     |   2011  
2    |  TR     |   2011  

....等等。此表有许多唯一的许可证编号,每个许可证类型和年份(从 2003 年到 2012 年)都列出。

我想要的是创建一个表格来显示这样的信息

Lic#  | Permit      | Year  
-----------------------------
1     |NS1          | 2003  
1     | NS1, NS2    | 2004  
2     | TR, NS2     | 2012  
3     | OR          | 2008  
2     | OR, NS1, TR | 2011
4

1 回答 1

3

正如我在评论中发布的那样,group_concat()在 MySQL 中使用该功能很容易,但是如果您想在 MS Access 中执行此操作,我认为您必须使用 VBA 来处理这个问题。

我建议你这个功能:

public function concatenatePermits(licNo as integer, year as integer)
    dim db as DAO.database, rec as DAO.recordset, strSQL as string
    dim ans as string

    set db = currentdb()
    strSQL = "select permit from [your table] " & _
             "where [lic#]=" & licNo & " and year=" & year & ";"
    set rec = db.openrecordset(strSQL, dbOpenDynaset, dbReadOnly)
    ans = ""
    with rec
        .moveFirst
        do
            if ans = "" then
                ans = !permit
            else
                ans = ans & "," & !permit
            end if
        loop until .EOF
    end with
    rec.close
    db.close
    concatenatePermits = ans
end function

此函数可用于任何查询。缺点:如果你的表真的很大,使用这个函数的查询的执行会很慢。我认为更好的方法是创建一个空表,然后使用 VBA 逐行填充它。

希望这对您有所帮助。


使用 VBA 添加行

在您的评论中,您询问如何使用 VBA 向表中添加行。假设该表存在并且您有要输入该表的数据,我建议您这样做:

public sub addData()
    dim db as dao.database, recOut as dao.recordset
    ' Declare all the variables you need for your code'
    set db = currentdb()

    ' recOut will be the table where you want to store your data '
    set recIn = db.openRecordset("tblYourOutTable",dbOpenDynaset,dbEditAdd)

    ' At some point in your code you will need to store data in your table: '
    with recOut
        .addNew
            ![A_Field] = value1
            ![Another_field] = value2
            ![Yet_another_field] = value3
        .update
    end with

    ' Close the recordset and the database objects '
    rec.close
    db.close
end sub
于 2013-04-09T23:52:16.813 回答