SQL分组项的最大平均值

时间:2015-03-11 12:30:24

标签: mysql sql

在线上商店建模,用户可以在其中购买物品并对他们购买的物品进行评级。有四个表

购买(用户,项目)

用户(UserID,名称)

费率(项目,评级)

项目(ItemID,描述,价格)

我想向每个用户返回他们没有购买的具有最高平均评分的项目列表。

到目前为止我构建的代码有点笨拙,但似乎只完成了一半的工作:

SELECT U.UserID, U.name, I.ItemID, I.Description, AVG(R.Rating) AS avgRate
FROM Item I, User U, Rates R 
WHERE R.Item=I.ItemID 
AND NOT EXISTS 
(SELECT Item  FROM Buys B  WHERE I.ItemID = B.item and U.UserID = B.user) 
group by U.UserID, item,I.ItemID Order by U.UserID, avgRate DESC

这给了我以下输出:

UserID   name   ItemID  Decription           avgRate
1        Jones   5      Computing Textbook   5
1        Jones   11     Tennis Ball          3.5
1        Jones   12     Tennis Raquet        4
2        Brown   5      Computing Textbook   5
2        Brown   11     Tennis Ball          3.5
2        Brown   12     Tennis Raquet        4

但我希望输出只为每个用户选择一个项目,所以:

UserID  name    ItemID  Decription           avgRate
1       Jones   5       Computing Textbook   5
2       Brown   5       Computing Textbook   5

我试过限制排序,但它只给了我一行,你不能使用AVG的MAX()函数......

1 个答案:

答案 0 :(得分:0)

对于您可能使用的同一用户,两种产品的平均价值绝不会相同:

with cte1 (UserID,name,ItemID,Decription,avgRate)
as
(
SELECT U.UserID, U.name, I.ItemID, I.Description, AVG(R.Rating) AS avgRate
FROM Item I, User U, Rates R 
WHERE R.Item=I.ItemID 
AND NOT EXISTS 
(SELECT Item  FROM Buys B  WHERE I.ItemID = B.item and U.UserID = B.user) 
group by U.UserID, item,I.ItemID Order by U.UserID, avgRate DESC
)
,
cte2 (UserID,name,ItemID,Decription,avgRate,rank1) as
(
select * , rank() over (partition by name order by avgrate)from cte1
)
select UserID,name,ItemID,Decription,avgRate from cte2 where rank1 in
(
select max(rank1) from cte2 group by userid
) 
order by userid