4

我有一张item_table这样的桌子:

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.

我不能移动到avgHaving因为其他条件取决于avg.

如何编写选择查询?

4

2 回答 2

6
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 小提琴示例 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 小提琴示例 2

于 2012-11-06T15:54:01.803 回答
1

您是否尝试将聚合放在子查询中,然后您有在子句avg()中使用的值:JOIN

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')))
于 2012-11-06T15:49:39.110 回答