嗨,我有一个表格,其中包含产品数量和每个产品的评分,由于某些原因,我有每个产品的不同行以及每个对其进行评分的人的比率,如下所示:
p1 2
p2 4
p3 4
p1 4
p1 5
p1 3
p2 7
我正在使用以下查询,但它显示了所有产品的平均费率,但我希望它单独显示每个产品的平均费率。
Select ProductName, AVG(Rate) FROM Products
只是GROUP BY productName
:
Select ProductName, AVG(Rate) AS 'Average Rate'
FROM Products
GROUP BY productName
编辑:要显示率最高的一个:
SELECT ProductName, Rate
FROM Products
ORDER BY rate DESC
LIMIT 1
编辑 2:要获得平均率最高的产品名称:
SELECT productname, AVG(rate) Avgrate
FROM Products
GROUP BY productname
HAVING AVG(rate) =
(
SELECT AVG(rate)
FROM Products
GROUP BY productname
ORDER BY AVG(rate) DESC
LIMIT 1
)
您需要添加分组依据。
Select ProductName, AVG(Rate) FROM Products GROUP BY ProductName
要对结果进行排序,请在 Group By 之后使用 Order By
Select ProductName, AVG(Rate) FROM Products GROUP BY ProductName ORDER BY ProductName
如果要降序排序,则上面的查询排序结果为升序,然后使用DESC
,
Select ProductName, AVG(Rate) FROM Products GROUP BY ProductName ORDER BY ProductName DESC
选择评级较高的产品
Select ProductName, AVG(Rate) FROM Products GROUP BY ProductName
HAVING AVG(Rate) = (SELECT MAX(AVG(Rate)) FROM Products GROUP BY ProductName)
此查询返回所有具有最高平均评分的产品。
只有一种评分较高的产品在降序中使用 LIMIT
Select ProductName, AVG(Rate) FROM Products GROUP BY ProductName
ORDER BY ProductName DESC
LIMIT 1