来自多个子查询MYSQL的视图

时间:2015-04-08 21:33:20

标签: mysql math subquery

我有一个需要两个子查询的数学代码。下面是代码的副本。

SELECT AVGTEMP_X.Average_Temp, ProduceMonAvg.Avergae_CPI,
SUM(AVGTEMP_X.Average_Temp) as AVGTEMPSUM,
SUM(ProduceMonAvg.Average_CPI) as PROCPISUM,
SUM(AVGTEMP_X.Average_Temp*AVGTEMP_X.Average_Temp) AS AVGTEMPSQ,
SUM(ProduceMonAvg.Average_CPI*ProduceMonAvg.Average_CPI)PROCPISQ,
SUM(AVGTEMP_X.Average_Temp*ProduceMonAvg.Average_CPI) AS PowerSum,
COUNT(*) as COUNT,
(COUNT*(PowerSum)-(AVGTEMPSUM))/(sqrt(COUNT*(AVGTEMPSQ)-pow(AVGTEMPSUM,2)*
    (COUNT*(PROCPISQ)-pow(PROCPISUM,2)))) AS Correlation
FROM(SELECT series_id,FORMAT(AVG(value),2) AS Average_CPI, period
FROM CURRENT
WHERE series_id = 'CUSR0000SEFK'
AND theYear >=(1997)
AND theYear <=(2010)
GROUP BY period) AS ProduceMonAvg,
(SELECT Average_Temp
FROM AVGTEMP_X)
INNER JOIN ProduceMonAvg
ON AVGTEMP_X.period = ProduceMonAvg.period

我收到错误说

  

1146 - 表&x; xxx.ProduceMonAvg&#39;不存在

     

1054 - 未知栏&#39; COUNT&#39;在&#39;字段列表&#39;

1 个答案:

答案 0 :(得分:0)

在外部查询中,您引用ProdcueMonAvg.Average_CPI等。在内部查询中,您将其别名为AS ProduceMonAvg。请注意拼写错误 - Prodcue vs Produce。您确定自己的错误不是Table xxx.ProdcueMonAvg doesn't exist吗?

就此而言,您的查询似乎还有其他一些问题。您加入AVGTEMP_X查询是使用子查询,其中一个不是必需的,它也执行交叉连接,然后是内连接。我怀疑那是你想要的。试试这个:

    SELECT AVGTEMP_X.Average_Temp,
    ProduceMonAvg.Average_CPI,
    SUM(AVGTEMP_X.Average_Temp) AS AVGTEMPSUM,
    SUM(ProduceMonAvg.Average_CPI) AS PROCPISUM,
     SUM(AVGTEMP_X.Average_Temp * AVGTEMP_X.Average_Temp) AS AVGTEMPSQ,
    SUM(ProduceMonAvg.Average_CPI * ProduceMonAvg.Average_CPI) PROCPISQ,
    SUM(AVGTEMP_X.Average_Temp * ProduceMonAvg.Average_CPI) AS PowerSum,
    COUNT(*) AS TOTAL,
     (COUNT(*) * (SUM(AVGTEMP_X.Average_Temp * ProduceMonAvg.Average_CPI)) - (SUM(AVGTEMP_X.Average_Temp))) / (sqrt(COUNT(*)* (SUM(AVGTEMP_X.Average_Temp * AVGTEMP_X.Average_Temp)) - pow(SUM(AVGTEMP_X.Average_Temp), 2) * (COUNT(*)* (SUM(ProduceMonAvg.Average_CPI * ProduceMonAvg.Average_CPI)) - pow(SUM(ProduceMonAvg.Average_CPI), 2)))) AS Correlation
FROM (
    SELECT series_id,
        FORMAT(AVG(value), 2) AS Average_CPI,
        period
    FROM CURRENT
    WHERE series_id = 'CUSR0000SEFK'
        AND theYear >= (1997)
        AND theYear <= (2010)
    GROUP BY period
    ) AS ProduceMonAvg
INNER JOIN AVGTEMP_X ON AVGTEMP_X.period = ProduceMonAvg.period

我还创建了一些模拟表和数据,最后测试了查询。它返回结果。你可以在这里看到它:http://sqlfiddle.com/#!9/47523/14