Select rating_id, average_rating
From (Select rating_id, avg(rating_num) as average_rating
from ratings
group by rating_id
having count(*) > 50)
HAVING average_rating > 4 ;
运行查询后,出现错误
每个派生表都必须有自己的别名
我知道这里的部分有效:
Select rating_id, avg(rating_num) as average_rating
from ratings
group by rating_id
having count(*) > 50
我在这个子查询中做错了什么?我搜索,搜索和搜索但无法找到错误,无论我在哪里纠正,我仍然会收到错误
答案 0 :(得分:3)
如错误消息所示,您需要为子查询添加别名:
SELECT rating_id, average_rating
FROM (
SELECT
rating_id,
AVG(rating_num) AS average_rating
FROM ratings
GROUP BY rating_id
HAVING COUNT(*) > 50
) AS some_alias
WHERE average_rating > 4
some_alias
可以是任何东西 - 或者是子查询的描述性名称,或者因为您永远不需要按名称引用子查询,所以您可以使用非描述性名称,例如T1(然后是T2,T3)等等,如果你有其他子查询)。
您也可以在外部查询中使用WHERE而不是HAVING。
答案 1 :(得分:2)
Select rating_id, average_rating
From (Select rating_id, avg(rating_num) as average_rating
from ratings
group by rating_id
having count(*) > 50) a
HAVING average_rating > 4 ;
请注意表别名“a”
答案 2 :(得分:1)
在子查询之后加上“SomeAlias”:
Select rating_id, average_rating
From (Select rating_id, avg(rating_num) as average_rating
from ratings
group by rating_id
having count(*) > 50) as A
HAVING average_rating > 4 ;