2012-11-06 37 views
0

我有一個表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

  1. 如果的項目年齡平均比3大,然後我做的:inner join price_table on pricetype = 'O' or pricetype = 'P'
  2. 如果沒有,那麼我這樣做: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我不能移動avgHaving

如何編寫select查詢?

回答

2
select * 
from (
    select item, avg(age) as AvgAge 
    from item_table 
    group by item 
) ia 
inner join price_table p on ia.item = p.item 
    and ((ia.AvgAge >= 3 and p.pricetype in ('O', 'P')) 
     or (ia.AvgAge < 3 and p.pricetype in ('O', 'P', 'V'))) 

SQL Fiddle Example 1

這可以簡化爲:

select * 
from (
    select item, avg(age) as AvgAge 
    from item_table 
    group by item 
) ia 
inner join price_table p on ia.item = p.item 
    and (p.pricetype in ('O', 'P') 
     or (ia.AvgAge < 3 and p.pricetype = 'V')) 

SQL Fiddle Example 2

1

你有沒有試着將聚集在子查詢,那麼你有JOIN子句中使用的avg()值:

select i.item, i.type, p.pricetype, p.price 
from 
(
    select avg(i.age) age, i.item, i.type -- not sure where type is coming from in your OP as it is not in the table you showed 
    from item_table i 
    group by i.item, i.type 
) i 
inner join price_table p 
    on i.item = p.item 
    and ((i.age>= 3 and p.pricetype in ('O', 'P')) 
     or (i.age < 3 and p.pricetype in ('O', 'P', 'V')))