Reputation: 5
I have two table, TABLE1 and TABLE2 in the following structure:
....|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|....
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|....
`
And I'd like to merged them like this:
....|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|
so I'd like to calculate the average temperature in this period (between start and end dates) in the new structure.
I tried the following query:
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
but it doesn't work and shows this message:
Column 'TABLE1.STARDATE' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Upvotes: 0
Views: 543
Reputation: 1270633
You need 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;
Upvotes: 1
Reputation: 31991
try like below by using subquery
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
you got the error because you used aggregate function avg
and select all the columns of table but nothing used in group by
Upvotes: 0