在基于表单字段的MS Access查询中选择TOP?

问题描述 投票:2回答:2

我有一个Access报告,其中Record Source引用了表单上的几个字段。它工作正常。这是为了简单,减去SELECT子句中的一堆字段:

SELECT
    pt.PA,
    pt.SpfCode
FROM
    PtHead AS pt
    LEFT JOIN tblProblems AS p ON pt.PA = p.PantagNo
WHERE
    pt.PA = [Forms]![fdlgQualityHistory]![PA] AND
    p.ComplaintDate >= [Forms]![fdlgQualityHistory]![StartDate];

我想升级此报告,以便它只显示最新的记录。这很好用:

SELECT TOP 20  -- NEW PART
    pt.PA,
    pt.SpfCode
FROM
    PtHead AS pt
    LEFT JOIN tblProblems AS p ON pt.PA = p.PantagNo
WHERE
    pt.PA = [Forms]![fdlgQualityHistory]![PA] AND
    p.ComplaintDate >= [Forms]![fdlgQualityHistory]![StartDate]
ORDER BY p.ComplaintDate DESC;  -- NEW PART

但是,我不希望它被硬编码到TOP 20。我希望它是TOP x,基于同一形式的另一个领域。以下失败:

SELECT TOP [Forms]![fdlgQualityHistory]![MaxProblems]  -- FAILS HERE
    pt.PA,
    pt.SpfCode
FROM
    PtHead AS pt
    LEFT JOIN tblProblems AS p ON pt.PA = p.PantagNo
WHERE
    pt.PA = [Forms]![fdlgQualityHistory]![PA] AND
    p.ComplaintDate >= [Forms]![fdlgQualityHistory]![StartDate]
ORDER BY p.ComplaintDate DESC;

错误:

SELECT语句包括拼写错误或缺失的保留字或参数名称,或标点符号不正确。

我可以改变语法来使其工作吗?如果没有,我该怎么办?每次通过VBA运行报表时,是否必须覆盖整个查询文本?

sql vba ms-access access-vba
2个回答
1
投票

Access does not support using a parameter for SELECT TOP.

修改该[Forms]![fdlgQualityHistory]![MaxProblems]控件的After Update事件中的Record Source SQL。


1
投票

或者,由于TOP数字无法参数化,因此使用表单字段,请考虑通过降序日期创建运行计数,然后可以过滤。但只需预先警告,对于较大的表,这种相关的子查询可能会带来性能挑战。

SELECT 
    pt.PA,
    pt.SpfCode
FROM
    PtHead AS pt
    LEFT JOIN tblProblems AS p ON pt.PA = p.PantagNo
WHERE
     pt.PA = [Forms]![fdlgQualityHistory]![PA]
 AND p.ComplaintDate >= [Forms]![fdlgQualityHistory]![StartDate]
 AND (SELECT Count(*) 
      FROM PtHead sub_pt
      LEFT JOIN tblProblems AS sub_p ON sub_pt.PA = sub_p.PantagNo
      WHERE sub_p.ComplaintDate >= p.ComplaintDate) <= [Forms]![fdlgQualityHistory]![MaxProblems];

也许有一天MS Access将支持窗口函数并加入RDBMS世界中的其他函数以避免相关的子查询:

ROW_NUMBER() OVER (ORDER BY pt.ComplaintDate DESC)
© www.soinside.com 2019 - 2024. All rights reserved.