在Access Query中运行for循环

时间:2014-07-09 15:42:01

标签: ms-access ms-access-2007

我有一个查询会生成已完成订单的2%财务或服务费用列表,其余额已逾期,这样可以正常使用。然后我有第二个查询,总计每个客户的财务费用(这一点也工作正常)我想要得到的第二个总计查询是逗号(或分号或空格或管道或...)分隔的订单列表在另一个领域

所以对于我的第一个查询:

CustomerID   OrderID        ContactName             FinanceChargeAmmount
   218        31901   Joe Schmoe Construction            23.43
   218        31927   Joe Schmoe Construction            15.78
   218        31929   Joe Schmoe Construction             8.91
   231        33403   Billy Bob Construction              0.43
   258        33369   XYZ Corp                            0.77
   258        33546   XYZ Corp                            1.23

我的第二个:

CustomerID   ContactName                 SumOfFinanceChargeAmmount
   218     Joe Schmoe Construction         48.12
   231     Billy Bob Construction           0.43
   258     XYZ Corp                         2.00

我想在第二个表中添加另一个列,如:

CustomerID   ContactName                 SumOfFinanceChargeAmmount     Orders
   218     Joe Schmoe Construction         48.12                   31901, 31927, 31929
   231     Billy Bob Construction           0.43                   33403
   258     XYZ Corp                         2.00                   33369, 33546

但无法找到循环查询的方法或获取总计值的列表,虽然我知道我应该能够在VBA中执行此操作但我试图避免这样做如果可能的话

1 个答案:

答案 0 :(得分:0)

我知道你说你想避开VBA,但我没有看到另一种方法。所以这是一个提案:

public function concatOrders(customerId as Integer) as String
    On Error GoTo Oops

    dim db as DAO.database, rec as DAO.recordSet
    dim ans as String : ans = ""
    dim first as Boolean : first = true
    dim strSQL = "select orderId from [yourTable] " & _
                 "where customerID=" & customerId & " order by orderId";
    set db = currentDb()
    set rec = db.openRecordset(strSQL, dbOpenDynaset, dbReadOnly)
    with rec
        .moveFirst
        do
            if first then
                first = false
            else
                strSQL = strSQL & ", "
            end if
            strSQL = strSQL & !orderId
            .moveNext
        loop until .EOF
        .close
    end with
    db.close
    function_exit:
        concatOrders = ans
        set rec = Nothing
        set db = Nothing
        exit function
    Oops:
        ' Handle the errors here
        goto function_exit
end function