【问题标题】:Run a for Loop in Access Query在 Access 查询中运行 for 循环
【发布时间】:2014-07-09 15:42:01
【问题描述】:

我有一个查询,它会为余额逾期的已完成订单生成 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 中执行此操作,但我会尽可能避免这样做

【问题讨论】:

  • 如果这是一个 MySQL 问题,我会简单地说:“使用 group_concat()。但是,据我所知,Access 中没有等效的功能,所以恐怕你会必须使用 VBA “手工”编写...并不难。这让我想到一个问题:您为什么要避免使用 VBA?
  • 我不是从查询中提取数据并使用它做某事 VBA 人我是如果单击按钮设置其他字段 = X 或进入子表单并添加带有 X 数据的行我将花费接下来的 3 天在 VBA 中搞砸它,但如果我可以在查询中做到这一点,我已经是那里的 3/4
  • 您可以在 vba 中创建一个可从 SQL 查询调用的函数...我认为这是最简单的方法
  • 您在寻找什么?
  • @serakfalcon 第一个看起来像我正在寻找的东西 Idk 我怎么错过了它可能没有正确地用词来搜索

标签: ms-access ms-access-2007


【解决方案1】:

我知道您说过要避免使用 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

【讨论】:

  • 如果您将循环中的所有 strSQL 更改为 ans 或 concatorders = ans to concatorders = strSQL,您的代码就可以工作
猜你喜欢
  • 1970-01-01
  • 2015-05-14
  • 1970-01-01
  • 2015-10-13
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 2018-06-12
相关资源
最近更新 更多