温馨提示:本文翻译自stackoverflow.com,查看原文请点击:sql - JOINing two sub-queries with calculated fields

sql - 结合两个带有计算字段的子查询

发布于 2020-03-29 21:55:31

我有两个表,其中包含有关两个小部件生产的信息。 Table1看起来像这样:

C

Table2看起来像这样:

在此处输入图片说明

我想计算每个小部件的平均产量,并按国家/地区代码(ADM0_A3)显示,以便结果看起来像这样(在此阶段不必担心丢失数据,例如BWA没有小部件1的产量)

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

我正在使用的MS ACCESS SQL查询在这里:

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

我检查了子查询,它们工作正常。但是,当我尝试加入查询时,收到此错误消息"Syntax error in FROM clause"我认为该解决方案相当简单,但我看不到它,因此不胜感激任何建议。提前致谢!

查看更多

提问者
PetGriffin
被浏览
17
Gordon Linoff 2020-01-31 18:51

您可以尝试这样做:

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;

我不确定UNION ALLFROM条款是否支持所有版本的MS Access 如果没有,您可以使用视图解决该问题。

发布
问题

分享
好友

手机
浏览

扫码手机浏览