SQL为每个用户最近修改了帖子

时间:2014-10-04 11:25:28

标签: sql sql-server database

这是我的表:

CREATE TABLE [dbo].[posts]
(
    [id] [int] IDENTITY(1,1) NOT NULL,
    [user_id] [int] NOT NULL,
    [date_posted] [datetime] NOT NULL,
    [date_modified] [datetime] NOT NULL,
    [content] [text] NOT NULL,

    CONSTRAINT [PK_posts] PRIMARY KEY CLUSTERED ( [id] ASC )
)

我的公司需要一个查询,该查询将获得每个用户最近修改过的帖子的帖子ID。谁能帮帮我吗?谢谢,

1 个答案:

答案 0 :(得分:3)

rank()函数应该可以解决问题:

SELECT user_id, id AS most_recent_post_id
FROM   (SELECT user_id, 
               id, 
               RANK() OVER (PARTITION BY user_id ORDER BY date_posted DESC) AS rk
        FROM   [posts]) p
WHERE  rk = 1