【问题标题】:Oracle SQL view with COUNT, AVG columns具有 COUNT、AVG 列的 Oracle SQL 视图
【发布时间】:2014-05-25 07:30:44
【问题描述】:

我有 3 个表,item、item_cagegory 和 category。 item 和 item_category 在 item_id 中链接,item_category 和 category 在 category_id 中链接。

我正在创建一个视图,其中列出了类别的 ID 和名称、每个类别中的项目数量并计算该类别中所有项目的平均租金。

我的所有代码似乎都可以工作,除了 AVG_RATE 似乎只是吐出费率(而不是每个类别的平均费率)。有什么建议吗?

CREATE VIEW V_CATEGORY AS   
    SELECT DISTINCT category.category_id, category.name,
    (SELECT COUNT(*) FROM item_category 
        WHERE item_category.category_id = category.category_id) 
        AS items_in_category, 
    (SELECT AVG(item.rate) FROM item_category 
        WHERE item_CATEGORY.item_id = item.item_id 
        GROUP BY item_category.category_id) 
        AS avg_rate
        FROM category
    INNER JOIN item_category ON category.category_id = item_CATEGORY.category_id
    INNER JOIN item ON item_category.item_id = item.item_id;

【问题讨论】:

    标签: sql oracle view inner-join average


    【解决方案1】:

    尝试像这样写select

    SELECT 
      category.category_id, 
      category.name,
      COUNT(item.item_id) as items_in_category,
      AVG(item.rate) as avg_rate
    FROM
      category
    INNER JOIN 
      item_category ON category.category_id = item_CATEGORY.category_id
    INNER JOIN 
      item ON item_category.item_id = item.item_id
    GROUP BY
      category.category_id, 
      category.name
    

    【讨论】:

    • 谢谢。不幸的是,当我尝试使用该 select 语句创建视图时,它失败并显示“ORA-00937: not a single group function”。
    • @reallybadatmath,我忘了添加 group by 子句……现在应该可以了。
    • 就像一个魅力。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 2018-06-10
    • 2014-03-26
    • 2023-04-04
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多