如何在访问中创建基于另一个 table 的条件和的计算列

How to create a calculated column in access that is based in a conditional sum of another table

在 MS ACCESS 2016 中可以在 table 中创建一个列,该列是另一个 table?

的条件 SUM

例子

Table 1 - 列

ID, NAME, TOTAL

Table 2 - 列

ID, NAME, IDREF, CUSTO

数据:

Table 1

ID | Name  | Total
---+-------+----------------------------------------------------------------
35 |  Test |  "SUM(CUSTO) of ALL ELEMENTS OF TABLE 2 WHERE table2.IDREF = table1.ID"

Table 2

ID | Name  | IDREF | CUSTO
---+-------+-------+--------
1  | Test  |  35   |   50
2  | Test  |  35   |   30
3  | abcd  |  12   |   30
4  | Test  |  35   |   10

结果应该是:

table 1

ID | Name | Total
---+------+------
35 | Test |  90      (50 + 30 + 10 from table 2 where idref = 35)

您可以使用子查询:

select t1.*,
       (select sum(t2.CUSTO)
        from table2 as t2
        where t2.idref = t1.id
       ) as total
from table1 as t1;

更有效地,考虑 JOIN 到 运行 中的聚合子查询仅 一次 而不是 SELECT 子查询 运行 s代表行。

SELECT t1.*, agg.Total
FROM table1 as t1
INNER JOIN
   ( SELECT t2.idref, SUM(t2.CUSTO) AS Total
     FROM table2 as t2
     GROUP BY t2.idref
   ) AS agg
ON agg.idref = t1.id

或者,根据 Allen Browne 的 optimizing query tips in MS Access:

,用精确保存的查询替换子查询以获得更高的效率

A subquery will be considerably faster than a domain aggregate function. In most cases, a stacked query will be faster yet (i.e. another saved query that you include as a "table" in this query.)

SELECT t1.*, q.Total
FROM table1 as t1
INNER JOIN mySavedAggQuery q
ON q.idref = t1.id