不知道如何编写简单的查询

时间:2012-09-23 10:04:59

标签: mysql sql sqlite

您好我有一张桌子,其中包含每个产品的数量和评级,由于某些原因我每个产品的行数不同,每个人的评分率如下:

p1 2
p2 4
p3 4
p1 4
p1 5
p1 3
p2 7

我正在使用以下查询,但它显示了所有产品的平均费率,但我希望它能单独显示每种产品的平均费率。

Select ProductName, AVG(Rate) FROM Products 

2 个答案:

答案 0 :(得分:2)

只需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
)

答案 1 :(得分:2)

您需要添加分组依据。

Select ProductName, AVG(Rate) FROM Products GROUP BY ProductName

排序结果使用分组后排序

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