我有一個表item_table
這樣的:聚集的加入ON子句
item age
--------------
1 1
1 6
2 2
我有另一臺price_table
這樣的:
item pricetype price
--------------------------
1 O 5
1 P 6
1 V 7
2 O 8
2 P 9
2 V 10
所以,我想內部連接上述兩個表。
select *
from item_table i
inner join price_table p
on ...
大約有一些條件on
:
- 如果的項目年齡平均比
3
大,然後我做的:inner join price_table on pricetype = 'O' or pricetype = 'P'
- 如果沒有,那麼我這樣做:
inner join price_table on pricetype = 'O' or pricetype = 'P' or pricetype = 'V'
所以有條件on
條件。
然後我寫這樣的查詢:給出
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'))
錯誤: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.
因爲其他條件取決於avg
我不能移動avg
到Having
。
如何編寫select查詢?