我有一张叫做收视率的表,看起来是这样的

Rating   |   Picid    |   User
   8           12          6
   7           12          6
   9           15          7
   5           16          7
   9           17          8
   10          2           8
   7           18          3
   10          22          12

I want to group the ratings based on the picid, but only choose the highest rated picid per user. I have the query like this already:

SELECT *, AVG(rating) AS total FROM ratings
  GROUP BY picid ORDER by total DESC

现在,查询将输出如下信息:
等级| Picid |用户
七点五一二六
9 15 7年
5167个
9 17 8年
10 2 8个
7183个
10 22 12年
因此,它成功地根据picid分组收视率,但我只希望每个用户有一个最高的收视率。我希望它输出如下信息:
等级| Picid |用户
七点五一二六
9 15 7年
10 2 8个
7183个
10 22 12年
看看它如何只允许每个用户拥有最高等级的picid?
如何修改查询以执行此操作?
如果你想进一步澄清我的问题,请告诉我。

最佳答案

您首先必须计算每个(Picid,User)组合的平均评级,然后在实际结果上找到group-wise maximum

SELECT Rating, PicID, User
FROM (
  SELECT   AVG(Rating) AS Rating, Picid, User
  FROM     ratings
  GROUP BY Picid, User
) t1 NATURAL JOIN (
  SELECT   MAX(Rating) AS Rating, User
  FROM     (
    SELECT   AVG(Rating) AS Rating, User
    FROM     ratings
    GROUP BY Picid, User
  ) t
  GROUP BY User
) t2

sqlfiddle上查看。

10-08 04:41