简体   繁体   中英

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

It is possible in MS ACCESS 2016 to create a column in a table that is a conditional SUM of another table?

Example

Table 1 - Columns

ID, NAME, TOTAL

Table 2 - Columns

ID, NAME, IDREF, CUSTO

Data:

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

The result should be:

table 1

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

You can use a subquery:

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

More efficiently, consider an aggregate subquery in JOIN to run only once and not SELECT subquery that runs for every row.

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

Alternatively, replace subquery with exact saved query for even more efficiency per Allen Browne's 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 (ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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