我有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;
答案 0 :(得分:3)
尝试像这样编写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