Search code examples
sqlms-access-2016

JOINing two sub-queries with calculated fields


I have two tables containing info about the production of two widgets. Table1 looks like this:

c

Table2 looks like this:

enter image description here

I want to calculate the average production of each widget and display by the country code (ADM0_A3), so that the results would look something like this (not that bothered about missing data at this stage eg. BWA has no production of widget1)

ADM0_A3   w1avg   w2avg
DZA      50000  3450000
AGO      86000    40000
BWA      blank        0
CMR       3500    blank

The MS ACCESS SQL query I am using is here:

SELECT Z.ccode, Z.ave_w1, A.ave_w2 
FROM 
(
    SELECT X.ADM0_A3 as ccode, 0.02 * X.sum_w1 / X.n_w1 AS ave_w1 
    FROM 
    (
        SELECT t1.ADM0_A3, SUM(t1.production) AS sum_w1, COUNT(t1.production) as n_w1 
        FROM Table1 t1
        GROUP BY t1.ADM0_A3
    ) X
) Z
JOIN
( 
    SELECT Y.ADM0_A3, 0.025 * Y.sum_w2 / Y.n_w2 AS ave_w2
    FROM 
    (
        SELECT t2.ADM0_A3, SUM(t2.production) AS sum_w2, COUNT(t2.production) as n_w2 
        FROM Table2 t2
        GROUP BY t2.ADM0_A3
    ) Y
) A
ON A.ADM0_A3 = Z.ccode

I checked the sub-queries and they work OK. However, when I try to JOIN the queries I get this error message "Syntax error in FROM clause". I think the solution is something fairly simple but I just can't see it so would appreciate any suggestions. Thanks in advance!


Solution

  • You can try doing this:

    SELECT adm0_a3, MAX(w1avg) as w1avg, MAX(w2avg) as w2avg
    FROM (SELECT t1.ADM0_A3, AVG(t1.production) * 0.02 as w1avg, NULL as w2avg
          FROM Table1 as t1
          GROUP BY t1.ADM0_A3
          UNION ALL
          SELECT t2.ADM0_A3, NULL, AVG(t2.production) * 0.02 as w1avg
          FROM Table1 as t2
          GROUP BY t2.ADM0_A3
         ) as t
    GROUP BY adm0_a3;
    

    I'm not sure if all versions of MS Access support UNION ALL in the FROM clause. If not, you can work around that using a view.