简体   繁体   English

Access 2010 SQL查询选择带有临时表的内部联接

[英]Access 2010 SQL query select inner join with temporary tables

In Access 2013 using VBA I am running an SQL query where a table (CUSTOMERS_TEMP) has a monthly_total which is the sum of sales_price in a temporary table (SALESHIST) taken from a SALESHIST_TEMP table. 在使用VBA的Access 2013中,我正在运行一个SQL查询,其中表(CUSTOMERS_TEMP)具有month_total,这是从SALESHIST_TEMP表获取的临时表(SALESHIST)中sales_price的总和。 I'm not sure why this is not working. 我不确定为什么这不起作用。

Dim SQL As String
SQL = "Update CUST " _
    & "SET CUST.Monthly_Total = SALESHIST.Monthly_Total " _
    & "FROM CUSTOMERS_TEMP AS CUST " _
    & "INNER JOIN (SELECT KEY, SUM(SALES_PRICE) AS MONTHLY_TOTAL FROM SALESHISTORY_TEMP GROUP BY KEY) AS SALESHIST " _
    & "ON CUST.Key = SALESHIST.Key "
DoCmd.RunSQL SQL

Consider DSum domain aggregate for an updateable query. 考虑针对可更新查询的DSum域聚合 Also consider saving your query as stored object in database as it is more efficient since Access engine can compile it for best execution plan. 还应考虑将查询另存为数据库中的存储对象,因为它效率更高,因为Access引擎可以编译该查询以获得最佳执行计划。 Also, avoid Key for column name as it is a reserved word . 另外,请避免将Key作为列名,因为它是保留字

SQL SQL

UPDATE CUSTOMERS_TEMP CUST 
SET CUST.Monthly_Total = DSum("SALES_PRICE", "SALESHISTORY_TEMP", 
                              "[Key]='" & CUST.[Key] & "'")

VBA VBA

CurrentDb.Execute "mySavedQuery", dbFailOnError

Finally, reconsider saving aggregate data in source tables as you can always query them as needed and avoid the storage resource. 最后,重新考虑将聚合数据保存在源表中,因为您始终可以根据需要查询它们,并避免使用存储资源。

In MS Access, the syntax for UPDATE / JOIN is different from SQL Server. 在MS Access中, UPDATE / JOIN的语法不同于SQL Server。

It looks like: 看起来像:

Update CUSTOMERS_TEMP AS CUST INNER JOIN
       (SELECT KEY, SUM(SALES_PRICE) AS MONTHLY_TOTAL
        FROM SALESHISTORY_TEMP
        GROUP BY KEY
       ) AS SALESHIST
       ON CUST.Key = SALESHIST.Key
    SET CUST.Monthly_Total = SALESHIST.Monthly_Total;

You can also write this as: 您也可以这样写:

Update CUSTOMERS_TEMP AS CUST
    SET CUST.Monthly_Total = (SELECT SUM(SALES_PRICE) AS MONTHLY_TOTAL
                              FROM SALESHISTORY_TEMP
                              WHERE SALESHISTORY_TEMP.Key = CUST.Key
                             )
    WHERE EXISTS (SELECT 1
                  FROM SALESHISTORY_TEMP
                  WHERE SALESHISTORY_TEMP.Key = CUST.Key
                 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM