如何联接两个不同的表以及两个日期之间的平均值

时间:2019-03-02 18:15:47

标签: mysql sql join

我有两个表,TABLE1和TABLE2具有以下结构:

TABLE1:

....|VALUE1| STARTDATE|   ENDDATE|....
....|1     |2015-01-01|2015.01.03|.... 
....|2     |2015-01-01|2015.01.04|.... 
....|3     |2015-01-02|2015.01.04|.... 
....|4     |2015-01-03|2015.01.05|....
....|5     |2015-01-03|2015.01.05|....
....|6     |2015-01-03|2015.01.06|....
....|7     |2015-01-04|2015.01.06|....
....|8     |2015-01-04|2015.01.08|....
....|N     |2015-01-04|2015.01.09|....

TABLE2:

          DATE|   TEMPERATURE|....
    2015-01-01|             1|.... 
    2015-01-02|             2|.... 
    2015-01-03|             1|.... 
    2015-01-04|             3|....
    2015-01-05|             2|....
    2015-01-06|             4|....
    2015-01-07|             3|....
    2015-01-08|             3|....
    2015-01-09|             3|....

`

我想像这样合并它们:

....|VALUE1| STARTDATE|   ENDDATE| AVG TEMPERATURE|
....|1     |2015-01-01|2015.01.03|             1.3|
....|1     |2015-01-01|2015.01.03|             1.3| 
....|2     |2015-01-01|2015.01.04|            1.75| 
....|3     |2015-01-02|2015.01.04|               2|
....|4     |2015-01-03|2015.01.05|               2|   
....|5     |2015-01-03|2015.01.05|               2|
....|6     |2015-01-03|2015.01.06|             2.5|
....|7     |2015-01-04|2015.01.06|               3|
....|8     |2015-01-04|2015.01.08|               3|
....|N     |2015-01-04|2015.01.09|               3|

所以我想计算新结构在此期间(开始日期和结束日期之间)的平均温度。

我尝试了以下查询:

select TABLE1.STARTDATE, TABLE1.ENDDATE,AVG(TABLE2.TEMPERATURE) as AVGTEMPERATURE
from TABLE1
left outer join TABLE2
on TABLE2.Date between TABLE1.STARDATE and TABLE1.ENDDATE

但是它不起作用并显示以下消息:

  

选择列表中的'TABLE1.STARDATE'列无效,因为它既不包含在聚合函数中也不在GROUP BY子句中。

2 个答案:

答案 0 :(得分:1)

您需要GROUP BY

select t1.STARTDATE, t1.ENDDATE, AVG(t1.TEMPERATURE) as AVGTEMPERATURE
from TABLE1 t1 left outer join
     TABLE2 t2
     on t2.Date between t1.STARDATE and t1.ENDDATE
group by t1.STARTDATE, t1.ENDDATE;

答案 1 :(得分:0)

尝试使用子查询,如下所示

   select b.*,a.* from from TABLE1 b
   left outer join 
   ( select t2.*,t1.avgtemp  from
    ( select VALUE1, avg(TEMPERATURE) as avgtemp from
    TABLE2 group by VALUE1 
    ) t1 join TABLE2 t2 on t1.VALUE1=t2.VALUE1
    ) a on on a.Date between b.STARDATE and b.ENDDATE

您收到错误消息是因为您使用了汇总函数avg并选择了表的所有列,但在分组依据中没有使用