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

时间:2018-06-29 01:11:07

标签: sql vba ms-access inner-join

在使用VBA的Access 2013中,我正在运行一个SQL查询,其中表(CUSTOMERS_TEMP)具有month_total,这是从SALESHIST_TEMP表中获取的临时表(SALESHIST)中sales_price的总和。我不确定为什么这行不通。

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

2 个答案:

答案 0 :(得分:1)

考虑DSum domain aggregate进行可更新的查询。还应考虑将查询另存为数据库中的存储对象,因为它效率更高,因为Access引擎可以编译该查询以获得最佳执行计划。另外,请避免使用 Key 作为列名,因为它是reserved word

SQL

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

VBA

CurrentDb.Execute "mySavedQuery", dbFailOnError

最后,重新考虑将聚合数据保存在源表中,因为您始终可以根据需要查询它们,并避免使用存储资源。

答案 1 :(得分:0)

在MS Access中,UPDATE / JOIN的语法不同于SQL Server。

它看起来像:

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;

您也可以这样写:

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
                 );