我试图将一个计数字段添加到访问表中,以便按时间顺序为另一个字段中的每个重复记录递增。
因此,每当“唯一大小写”重复时,“计数器”就增加1。这也是按时间顺序排列,因此重复项从最早的重复项(例如)开始向上编号1。
Counter | UniqueCase | ResolvedDate
1 3312 01/01/2018
1 6374 01/01/2018
2 6374 02/01/2018
1 8546 15/03/2019
2 8546 18/03/2019
3 8546 12/05/2019
以下查询适用于这种情况:
SELECT
(SELECT COUNT(*)
FROM [COMEBACKTEST2]
AS TMP
WHERE [UNIQUECASE]=[COMEBACKTEST2].[UNIQUECASE]
AND [KEY]<=[COMEBACKTEST2].[KEY]
) AS [COUNTER],
*
INTO [Comeback 3]
FROM COMEBACKTEST2
ORDER BY COMEBACKTEST2.UniqueCase, COMEBACKTEST2.ResolvedDate;
当我“查看”此结果时,花了几秒钟,我可以看到结果是正确的(我扫描了几千行)。但是,尝试“运行”时,即使将其放置几个小时也无法完成。
此查询是否有更有效的版本,因为在当前状态下它似乎过于密集而无法实际工作?
我猜它完全需要一种不同的方法? 任何帮助将不胜感激,谢谢!
上面的示例丢失了格式,对不起: enter image description here
答案 0 :(得分:1)
Access SQL优化器并不复杂,因此很可能会为外部查询的每一行重新运行嵌套查询,因此要花很长时间运行整个SELECT INTO。通常最好避免在SELECT子句中使用嵌套查询,而应加入聚合查询。困难在于基于不等式对记录进行计数。为此,我们利用交叉联接(即笛卡尔乘积),然后仅在乘积的一侧对键值进行分组。
SELECT COUNTER.Sequence, t3.*
INTO [Comeback 3]
FROM COMEBACKTEST2 AS t3 JOIN
(SELECT Count(t1.KEY) AS Sequence, t1.UNIQUECASE, t1.KEY
FROM COMEBACKTEST2 AS t1, COMEBACKTEST2 AS t2
WHERE ((t2.UNIQUECASE = t1.[UNIQUECASE]) AND (t2.KEY <= t1.[KEY]))
GROUP BY t1.UNIQUECASE, t1.KEY
) AS [COUNTER]
ON (t3.UNIQUECASE= COUNTER.UNIQUECASE) AND (t3.KEY = COUNTER.KEY)
ORDER BY t3.UNIQUECASE, COUNTER.Sequence;
仍然最好具有适当的索引。在这种情况下,请确保[UniqueCase]和[Key]上有单独的索引。
如果要与示例列一起返回的其他列,则需要上述表格。但是,只要[ResolvedDate]与指定的[Key]值按时间顺序对应,那么所有发布的列都可以在单个查询中获得:
SELECT Count(t1.KEY) AS Sequence, t1.UNIQUECASE,
t1.KEY, Max(t2.ResolvedDate) AS ResolvedDate
FROM COMEBACKTEST2 AS t1, COMEBACKTEST2 AS t2
WHERE ((t2.UNIQUECASE = t1.[UNIQUECASE]) AND (t2.KEY <= t1.[KEY]))
GROUP BY t1.UNIQUECASE, t1.KEY
ORDER BY t1.UNIQUECASE, t1.KEY;