sql - 连接 ON 子句的聚合

标签 sql sql-server

我有一张 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.
    我动不了 avgHaving因为其他条件取决于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/

    相关文章:

    php - 是否可以自行连接单个表?

    sql - 查找窗口中 n 个类别之间的变化之前的最大值(类别之间有 m>n 个变化)

    sql-server - 将时间戳数据类型更改为 rowversion

    sql - tSQL 不在查询中

    sql - SQL表插入小数时溢出错误

    asp.net - SQL Server 2008 在什么数据类型中存储哈希密码

    mysql - 查询 |处理多个具有潜在空值的 where 条件

    mysql - 删除尾随空格并将其添加为前导空格

    sql - SQL中的循环行

    mysql - 插入后 1 天自动删除行(MySQL)