2014-04-01 26 views
0

我试图更新的滚动平均值计算一个临时表(MS Access 2010中)更新表从自身

作为一个选择查询,这个工程来计算3个月的移动平均值,但慢,所以我宁愿存储,只有在必要时更新的值:

SELECT tempQORDistGrouped.Type, tempQORDistGrouped.Supplier, tempQORDistGrouped.DepBkMo, tempQORDistGrouped.Amt, tempQORDistGrouped.Brands, tempQORDistGrouped.T2, tempQORDistGrouped.Brand, (select avg(rolavg.Amt) from tempQORDistGrouped as rolavg 
    where rolavg.Type = tempQORDistGrouped.Type 
    and rolavg.Supplier = tempQORDistGrouped.Supplier 
    and rolavg.Brands = tempQORDistGrouped.Brands 
    and rolavg.Brand = tempQORDistGrouped.Brand 
    and rolavg.DepBkMo between dateadd("m",-2,tempQORDistGrouped.DepBkMo) and tempQORDistGrouped.depbkmo) AS AvgAmt 
FROM tempQORDistGrouped; 

我试过下面的更新查询,但我觉得我的内部联接语法糟糕,因为它不会承认x1.Type为一个有效的字段(我是否需要将这些字段作为内部连接字段的一部分而不是在where子句中?):

UPDATE tempQORDistGrouped AS x1 
INNER JOIN (SELECT itmID, avg(Amt) AS RolAvg 
    FROM tempQORDistGrouped 
    WHERE tempQORDistGrouped.Type = x1.Type 
    AND tempQORDistGrouped.Brand = x1.Brand 
    AND tempQORDistGrouped.Brands = x1.Brands 
    AND tempQORDistGrouped.T2 = x1.T2 
    AND tempQORDistGrouped.DepBkMo between dateadd("m",-2,x1.DepBkMo) and x1.DepBkMo 
    GROUP BY itmID 
) AS x2 
ON x1.itmID = x2.itmID 
SET x1.3MonthRollingAmt = x2.RolAvg; 

干杯

回答

0

未经测试,但应该工作。 我做了列级查询计算AVG,然后映射回列的其余

试试这个:

UPDATE tempQORDistGrouped AS x1 
INNER JOIN (
    SELECT itmID 
     , (
      SELECT avg(Amt) amt 
      FROM tempQORDistGrouped x4 
      WHERE x4.Type = x3.Type 
       AND x4.Brand = x3.Brand 
       AND x4.Brands = x3.Brands 
       AND x4.T2 = x3.T2 
       AND x4.DepBkMo BETWEEN dateadd("m", - 2, x3.DepBkMo) AND x3.DepBkMo 
      ) AS RolAvg 
     , x3.Brand 
     , x3.Brands 
     , x3.DepBkMo 
     , x3.T2 
    FROM tempQORDistGrouped x3 
    ) AS x2 
    ON x1.itmID = x2.itmID 
     AND x1.Brand = x2.Brand 
     AND x1.Brands = x2.Brands 
     AND x1.T2 = x2.T2 
     AND x1.DepBkMo BETWEEN dateadd("m", - 2, x2.DepBkMo) AND x2.DepBkMo  
SET x1.3MonthRollingAmt = x2.RolAvg; 
+0

感谢SoulTrain,这给一去,只好修复它为一个小的语法错误,但现在我得到错误“操作必须使用可更新的查询”从Access时,我尝试执行。因为我在更新表格,所以没有意义。谷歌搜索,找不到任何解决它的工作,所以如果有人有这个想法,这将是伟大的! – gpark

+0

我在sql server env中试过这个,它工作正常,我没有MS访问设置来检查。您可以将查询更改为Select并查看它是否在Access中返回正确的结果。 – SoulTrain