获得每位用户得分最高的帖子

时间:2014-05-09 07:30:10

标签: mysql sql sql-server database

鉴于这两个表:

用户:

Name    UserId  
-----------
Pump 1  1   
Pump 1  2
Pump 1  3
Pump 2  4
Pump 2  5
Pump 2  6

文章:

PostId      UserId  Score

1           3       5
2           1       8
3           3       3
4           1       2
5           2       8
6           2       1

如何获得每个用户获得最高分数的帖子?

我能做的最好的事情是:

select Users.UserId as UserID, Posts.PostId as PostsID, Max(Posts.Score) as Score
from Users
inner join Posts on Posts.UserId = Users.UserId
Group by Users.UserId, Posts.PostsId

并没有给我错误的答案。

4 个答案:

答案 0 :(得分:3)

如果您使用的是SQL-Server,则可以使用ROW_NUMBERDENSE_RANK之类的排名功能:

WITH CTE AS
(
  SELECT u.UserId as UserID, p.PostId as PostsID, p.Score,
         RN = ROW_NUMBER() OVER (PARTITION BY u.UserId  ORDER BY Score DESC)
  FROM dbo.Users u
  INNER JOIN dbo.Posts p on p.UserId = u.UserId
)
SELECT UserID, PostsID, Score
FROM CTE
WHERE RN = 1

DEMO

在MySql中,这应该有效:

SELECT Users.userid     AS UserID, 
       Posts.postid     AS PostsID, 
       Max(Posts.score) AS Score 
FROM   Users 
       INNER JOIN Posts 
               ON Posts.userid = Users.userid 
GROUP  BY Users.userid

虽然PostID在某种程度上是任意的。

DEMO

答案 1 :(得分:1)

Select T.PostId,
       S.UserID,
       S.MAXSCORES
From TBL1 T INNER JOIN 
(SELECT MAX(SCORE) MAXSCORES
           ,UserID
     FROM TBL1 Group BY UserID) S On
S.UserID= t.UserID and s.MAXSCORES= t.score;

Fiddle Demo

答案 2 :(得分:1)

您只需要表格帖子来选择此结果。

select p1.UserId, p1.PostId, p1.Score
from Posts p1
--  inner join Users u on p1.UserId = u.UserId
where not exists 
   (select * 
    from Posts p2 
    where p1.UserId = p2.UserId and p1.Score < p2.Score);

答案 3 :(得分:1)

查询:

<强> SQLFIDDLEExample

SELECT u.Name,
       u.UserId,
       p.PostId,
       p.Score
FROM Users u
  JOIN Posts p
    ON p.UserId = u.UserId
  LEFT JOIN Posts p1
    ON p1.UserId = p.UserId
    AND p1.Score > p.Score
WHERE p1.Score is null

结果:

|   NAME | USERID | POSTID | SCORE |
|--------|--------|--------|-------|
| Pump 1 |      3 |      1 |     5 |
| Pump 1 |      1 |      2 |     8 |
| Pump 1 |      2 |      5 |     8 |