我想使用其他表中的数字更新表格,我想执行以下formla
X-Y(1) - (A1 + A2 + A3)
X是表格table1,而来自table2的是Y,A1,A2,A3。新记录将在列X中更新,其中ID只有一个记录= 0
表1
ID || X
-------------
1 || **0**
1 || 155
2 || 4
3 || 0
3 || 0
3 || 234
4 || 0
4 || 0
表2
ID || Y || A1 || A2 || A3
--------------------------------------
1 || 228 || 1 || 3 || 4
2 || 112 || 6 || 7 || 7
3 || 4 || 22 || 1 || 0
4 || 78 || 76 || 6 || 2
从上面的示例表中,唯一与certiria匹配的列是ID = 1,其中只有一列是0而count = 2所以列X 其中= 0将被更新(X2 = 228-155-(1 + 3 + 4))
更新了table1
ID || X
-------------
1 || **65**
1 || 155
2 || 4
3 || 0
3 || 0
3 || 234
4 || 0
4 || 0
我的代码是
Private Sub GET_TWO_INJLINE_EST()
DoCmd.SetWarnings False
DoCmd.RunSQL "UPDATE table1 I, table2 P" _
& " SET I.X = IIf(I.X = 0, DLookup(""P.Y-I.X-(P.A1 + P.A2 + P.A3)"" , " _
& " ""table1"", ""[ID]="" & [ID] & "" AND I.X <> 0""), I.X)" _
& " WHERE I.[ID] IN (SELECT I.[ID] FROM table1 I" _
& " GROUP BY I.[ID] HAVING (Count(I.[ID]) = 2)" _
& " AND (Min(I.ID) <> Max(I.X))" _
& " AND (Min(I.X) = 0 OR Max(I.X) = 0))" _
& " AND I.ID=P.ID"
DoCmd.SetWarnings True
End Sub
当我跑的时候告诉我&#34;未知&#34;错误。
答案 0 :(得分:0)
尝试将第二个 table1 I 更改为 table1 J 并更新对第二个 table1 的所有引用
UPDATE table1 I, table2 P
Set I.X = IIf(I.X = 0,
DLookup(""P.Y-I.X-(P.A1 + P.A2 + P.A3)"",
""table1"",
""[ID]="" & [ID] & "" AND I.X <> 0""
),
I.X
)
WHERE I.[ID] IN (
SELECT J.[ID] FROM table1 J
GROUP BY J.[ID]
HAVING (Count(J.[ID]) = 2)
AND (Min(J.ID) <> Max(J.X))
AND (Min(J.X) = 0 OR Max(J.X) = 0))
AND J.ID=P.ID
答案 1 :(得分:0)
在您尝试在字符串表达式中传递UPDATE ... INNER JOIN
时,请考虑DLookUp
查询并协调I.X
。此外,子查询的Min() <> Max()
等式与同一X不相同。
最后,考虑将更新查询保存为存储的Access查询,而不在VBA字符串中连接,这样可以避免双引号,并强制您在保存之前检查语法错误。此外,数据库引擎缓存并预编译以获得最佳执行计划。
SQL (另存为Access存储查询;请参阅较大表达式中的DMax)
UPDATE table1 I
INNER JOIN table2 P ON I.ID = P.ID
SET I.X = IIF(I.X=0, (P.Y - DMax("X", "table1", "ID=" & I.ID) - (P.A1+P.A2+P.A3)), I.X)
WHERE I.[ID] IN
(SELECT sub.[ID]
FROM table1 sub
GROUP BY sub.[ID]
HAVING (Count(sub.[ID]) = 2)
AND (Min(sub.X) <> Max(sub.X))
AND (Min(sub.X) = 0 OR Max(sub.X) = 0))
<强> VBA 强>
Private Sub GET_TWO_INJLINE_EST()
DoCmd.SetWarnings True
DoCmd.OpenQuery "mySavedUpdateQuery"
DoCmd.SetWarnings True
End Sub