【问题标题】:MS-Access select the greatest value less than current value matching criteriaMS-Access 选择小于当前值匹配条件的最大值
【发布时间】:2017-12-26 18:01:24
【问题描述】:

我的情况是我有一张简化后的表格,如下所示:

Sort| IsHeader
1   | 0
2   | 0
3   | 1
4   | 0
5   | 0
6   | 1
7   | 0
8   | 0
9   | 0

我正在尝试进行一个查询,该查询将为每个详细信息行更新一个新的 HeaderSort 行,以显示该行属于哪个标题,最终结果如下:

Sort| IsHeader| HeaderSort
1   |  0      | 0
2   |  0      | 0
3   |  1      | 3
4   |  0      | 3
5   |  0      | 3
6   |  1      | 6
7   |  0      | 6
8   |  0      | 6
9   |  0      | 6

在 T-SQL 中我可以很容易地做到这一点:

update MT set HeaderSort = 
(
    select isnull(max(Sort),0) from MyTable where Sort <= MT.Sort and IsHeader = 1
)  as HeaderSort 
from MyTable MT

我的访问版本尝试如下:

Update MyTable set HeaderSort =
(
    select nz(max(Sort),0) from MyTable where Sort <= MT.Sort and IsHeader = 1
)

但是,这给出了“操作必须使用可更新查询”。错误。 是我获取值的逻辑错误,还是只是一些 ms-access 语法?

【问题讨论】:

    标签: sql ms-access jet


    【解决方案1】:

    操作必须使用可更新的查询。是当更新语句中引用的所有表都不是可更新的时遇到的一般错误。不幸的是,很少有子查询。

    您可以通过使用DLookup 而不是子查询来解决该错误:

    Update MyTable set HeaderSort = DLookUp("nz(max(Sort),0)", "MyTable", "Sort <= " & MyTable.Sort & " and IsHeader = 1")
    

    【讨论】:

    • 这不是真的。据我所知,DLookUp 不是真正的域聚合,而是返回第一个结果的记录集包装器。您可以在DLookUp 中使用聚合和表达式。 DLookUp("Max(Field1)", "MyTable") 只是优化程度较低的等于 DMax("Field1", "MyTable")
    • 我想我一直在考虑将它完全放在一个 sql 语句中,但就我的目的而言,DLookup 方法工作得很好。
    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 2019-01-01
    • 2019-05-09
    • 2015-11-04
    • 1970-01-01
    • 2017-12-07
    • 2020-08-10
    • 1970-01-01
    相关资源
    最近更新 更多