按2个值之间的平均评分排序

时间:2015-08-21 02:29:33

标签: mysql sql

我有一个名为ranks的表,它存储1-7值并将其与项目和用户ID相关联。商品的评级是给出的所有评级的平均值。

排名表:id | userid | value | itemid.

按平均最高评分排序,我这样做(来自这里的答案):

select avg(value), itemid
from ranks
group by itemid
order by avg(value) desc

但是,我还希望能够过滤具有特定评级的项目,而不仅仅是最高评级 - >评分最低。例如,平均评分为5和6的项目。

select avg(value), itemid
from ranks
having avg(value) between 5 and 6
group by itemid
order by avg(value) desc

这给了我group by的非特定错误。有人能指出我正确的方向吗?

3 个答案:

答案 0 :(得分:1)

select * from
(
select avg(value) as avgval, itemid
from ranks
group by itemid) t
where avgval between 5 and 6;

您可以使用子查询来完成。

答案 1 :(得分:1)

您的having条款需要在您的group by条款之后,所以只需颠倒它们出现的顺序:

select avg(value), itemid
from ranks
group by itemid
having avg(value) between 5 and 6
order by avg(value) desc

答案 2 :(得分:0)

with Temp as 
(
select avg(value) [rating], itemid
from ranks
)
Select * from Temp
Where rating between 5 and 6
group by itemid
order by rating desc