加入ON子句的聚合

时间:2012-11-06 15:45:23

标签: sql sql-server

我有一张像这样的表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'
  3. 因此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移至Having,因为其他条件取决于avg

    如何编写选择查询?

2 个答案:

答案 0 :(得分:3)

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 :(得分: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')))