首页 > 解决方案 > 我想用上个月的数据填充列中的空白字段

问题描述

表模型 我有一个名为“MYSTERY_SHOPPER”的表,其中加载了月度数据。如图所示,2 月已加载,但“Lista de Precio”列中没有值,因此我需要加载上个月的值,比较“Modelo”列中加载的模型是否相同作为最后一个月。

Dim rs As Recordset

    Dim datefield As String
    Dim modelfield As String
    Dim pricefield As String

    Dim modeldict As Object

    Set modeldict = CreateObject("Scripting.Dictionary")

    Set rs = CurrentDb.OpenRecordset("MYSTERY_SHOPPER")

    With rs
        .MoveFirst
        Do Until .EOF
            datefield = ![Fecha]
            modelfield = ![Modelo]
            If Not IsNull(![Precio de Lista]) Then
                pricefield = ![Precio de Lista]
                If Not modeldict.Exists(modelfield) Then
                    modeldict.Add modelfield, datefield & "|" & pricefield
                Else
                    If Split(modeldict(modelfield), "|")(0) < datefield Then
                        modeldict(modelfield) = datefield & "|" & pricefield
                    End If
                End If
            Else
                .Edit
                ![Precio de Lista] = Split(modeldict(modelfield), "|")(1)
                .Update
            End If
            .MoveNext
        Loop
    End With

我想到了类似的东西,但它不起作用,它没有做任何事情。

请帮忙。

标签: sqlvbams-access

解决方案


您可以使用update查询填充空价格,如下所示:

update mystery_shopper m
set 
    m.[precio de lista] =
    dlookup
    (
        "[precio de lista]",
        "mystery_shopper",
        "modelo = '" & m.modelo & "' and fecha = " & 
        format
        (
            nz
            (
                dmax
                (
                    "fecha",
                    "mystery_shopper",
                    "modelo = '" & m.modelo & "' and fecha < " & 
                    format(m.fecha,"\#mm\/dd\/yyyy\#")
                )
                ,#1901-01-01#
            )
            ,"\#mm\/dd\/yyyy\#"
        )
    )
where
    m.[precio de lista] is null or m.[precio de lista] = 0

我已经求助于使用域聚合函数dlookup,并且dmax我相信使用相关子查询来获取最新价格会导致查询变得不可更新,尽管可能有更好的方法来解决这个问题。


或者,您可以通过 3 个步骤解决此问题:

  1. 执行查询以创建一个临时表,其中包含每个 的最新价格modelo

    select m.modelo,
        (
            select top 1 n.[precio de lista]
            from mystery_shopper n
            where n.modelo = m.modelo and n.fecha < m.fecha
            order by n.fecha desc
        ) as precio
    into temp_table
    from
        mystery_shopper m
    where
        m.[precio de lista] is null or
        m.[precio de lista] = 0
    
  2. 使用update查询更新表中的价格,mystery_shopper从临时表中获取数据:

    update mystery_shopper m inner join temp_table t on m.modelo = t.modelo
    set m.[precio de lista] = t.precio
    where 
        (m.[precio de lista] is null or m.[precio de lista] = 0) and
        t.precio is not null and
        t.precio <> 0
    
  3. 删除临时表:

    drop table temp_table
    

推荐阅读