我有一张 table item_table
像这样:
item age
--------------
1 1
1 6
2 2
我有另一张 table
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
至 Having
因为其他条件取决于avg
.如何编写选择查询?
最佳答案
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
关于sql - 连接 ON 子句的聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13254504/