I have a table item_table like this:
item age
--------------
1 1
1 6
2 2
I have the other table price_table like this:
item pricetype price
--------------------------
1 O 5
1 P 6
1 V 7
2 O 8
2 P 9
2 V 10
So, I want to inner join above two tables.
select *
from item_table i
inner join price_table p
on ...
There are some conditions about the on:
- if the average of age of an item is bigger than
3, then I do:inner join price_table on pricetype = 'O' or pricetype = 'P' - If not, then I do:
inner join price_table on pricetype = 'O' or pricetype = 'P' or pricetype = 'V'
So there are conditions for on conditions.
I then write the query like this:
select i.item, i.type, p.pricetype, p.price
from item_table i
inner join price_table p on i.item = p.item
and (avg(i.age) >= 3 and p.pricetype in ('O', 'P'))
or (avg(i.age) < 3 and p.pricetype in ('O', 'P', 'V'))
The error is given: An aggregate cannot appear in an ON clause unless it is in a subquery contained in a HAVING clause or select list, and the column being aggregated is an outer reference.
I can’t move the avg to Having because other conditions are depending on the avg.
How can I write the select query?
SQL Fiddle Example 1
This can be simplified to:
SQL Fiddle Example 2