根据Access中的另一列更新列

时间:2017-01-12 10:24:09

标签: sql ms-access

我有这个问题:

SELECT ID, T2.code1, T2.code2, T2.mins
FROM Table AS T1, (
SELECT code1, code2, MIN(ID) AS mins
FROM Table GROUP BY code1, code2 HAVING count(*)>1
)  AS T2
WHERE T1.code1=T2.code1 And T1.code2=T2.code2;

我获取所有基于code1和code2的重复行并获取重复行的最小ID。

现在我要做的是更新表格,将重复行的ID设置为最小值

我试过这个,但在访问时遇到错误:(操作必须使用可更新的查询)

Update (
SELECT ID, T2.code1, T2.code2, T2.mins
FROM Table AS T1, (
SELECT code1, code2, MIN(ID) AS mins
FROM Table GROUP BY code1, code2 HAVING count(*)>1
)  AS T2
WHERE T1.code1=T2.code1 And T1.code2=T2.code2
) Set ID=T2.mins;

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

考虑使用临时表,使用聚合片的生成表操作查询,然后加入UPDATE。 Access SQL需要更新查询以保留updateable (or non read-only)条件,这通常意味着直接表和简单连接查询或您可以在其数据表视图中编辑/添加/删除的任何表/查询。使用GROUP BY的聚合查询永远不可更新。

制作表查询

SELECT code1, code2, MIN(ID) AS mins 
INTO Temp
FROM Table 
GROUP BY code1, code2 
HAVING COUNT(*)>1;

更新查询

UPDATE Table t1 INNER JOIN Temp t2
ON t1.code1 = t2.code1 AND t1.code2 = t2.code2
SET t1.Col = t2.Mins;

或者,尝试使用DMax()DMin()DCount()等域聚合。以下假设代码字段是数字类型:

UPDATE Table t1
SET t1.Col = DMin("ID", "Table", "code1=" & t1.code1 & " AND code2=" & t1.code2)
WHERE DCount("ID", "Table", "code1=" & t1.code1 & " AND code2=" & t1.code2) > 1