将对应字段中的值更新为另一个字段的最小值

时间:2017-01-12 16:32:28

标签: sql ms-access access-vba

我看过几篇帖子,讨论如何在Update查询中使用聚合函数。但是,这些帖子与我的问题有很大不同,我无法提出解决方案。

我有一个名为tblDistanceCalc的临时表(见下文)字段ClosestCity实际上不是距离原点最近的城市,而是包含该州的许多其他城市(我选择的)。然后是从Origin到" ClosestCity"在距离场中。 Region字段表示最近城市的Region。

tblDistanceCalc
Origin \\ ClosestCity \\ Distance \\ Region

然后我有另一个我想要更新的表名为tblnewbid。它有Origin,Destination字段。我的代码为O_CityRegion和D_CityRegion创建了字段,然后继续使用。

tblnewbid
Origin \\ Destination \\ O_CityRegion \\ D_CityRegion

我需要将tblnewbid中的Origin与tblDistanceCalc中的Origin匹配的代码,在Distance字段中找到该Origin的最小距离,并将相应字段中的Region返回到Minimum Distance。

为了解决这个问题,我打算简化我的代码,但我想完整地展示它。如果可以,请忽略,我从表单中的文本框中获取表名。我知道这部分有效。我的问题是更新查询

这是我到目前为止所做的:

Private Sub btnInsertClosestCityRegion_Click()
Dim strSQL As Variant
Dim rs1 As DAO.Recordset
Dim db As Database
Dim FSO As New FileSystemObject
Dim tblnewbid As String
Dim Distance As Integer


Set db = CurrentDb

tblnewbid = FSO.GetBaseName(Me.txtFileName)
Debug.Print tblnewbid

db.Execute "ALTER TABLE " & tblnewbid & " ADD COLUMN O_CityRegion CHAR", dbFailOnError
db.Execute "ALTER TABLE " & tblnewbid & " ADD COLUMN D_CityRegion CHAR", dbFailOnError

Set rs1 = db.OpenRecordset("Select [Origin] FROM " & tblnewbid & " ; ")


rs1.MoveFirst

    strSQL = "UPDATE " & tblnewbid & " INNER JOIN [tblDistanceCalc]"
    strSQL = strSQL & " ON [tblDistanceCalc].[Origin] = " & tblnewbid & ".[Origin]"
    strSQL = strSQL & " SET " & tblnewbid & ".[O_CityRegion]=[tblDistanceCalc].[Region] WHERE tblDistanceCalc.Distance = (SELECT DMIN(Distance) FROM tblDistanceCalc)"


    db.Execute (strSQL), dbFailOnError


rs1.Close

Set rs1 = Nothing
Set db = Nothing

DoCmd.Hourglass False
MsgBox "The proxity of the city within the states have been added!"
End Sub

0 个答案:

没有答案