例如,我有下表,其中包含产品的用户评论
tblreviews
ID | product | review|
==========================
1 | pen | 2 |
2 | pen | 2 |
3 | ink | 1 |
4 | ink | 1 |
我想写一个查询,它会为每个项目添加值,然后给我前五名,在这个例子中我需要提取数据:
-
select sum (review) from tblreviews where product name= 'pen'
select count (pen) from tblreviews where product name= 'pen'
然后我可以根据它们的结果来计算平均评价,但是我必须对表格中的每个产品都这样做,然后这将给我一个最高评价的产品列表,这就是我&# 39;我试图得到。
这样做会更容易吗?
答案 0 :(得分:2)
您可以使用分组
Select product, avg(review) as average
From tblreviews
Group by product
Order by average desc
Limit 5
答案 1 :(得分:0)
平均评价前5位的产品:
SELECT product, AVG(review) AS Average_review
FROM tblreviews
GROUP BY product
ORDER BY Average_review DESC
LIMIT 5