每个用户ID限制3行

时间:2017-08-30 17:45:05

标签: sql postgresql greatest-n-per-group

我有一个查询:

SELECT users.id, users.name, messages.id, messages.name

FROM messages
INNER JOIN users on messages.user_id = users.id

WHERE users.active = true

ORDER BY users.id, messages.sent_at

我想要的是查询返回每个users.id的前3行,是否可能?

我没有在stackoverflow或任何其他网站上找到任何与此相似的问题。我感谢任何答案或有用的链接。感谢

1 个答案:

答案 0 :(得分:4)

您可以在子查询/派生表中使用row_number()

select users_id, users_name, messages_id, messages_name
from (
  SELECT users.id as users_id, users.name as users_name, messages.id as messages_id, messages.name as messages_name, messages.sent_at
    , row_number() over (partition by users.id order by messages.sent_at) as rn
  FROM messages
  INNER JOIN users on messages.user_id = users.id
  WHERE users.active = true
) as sub
where rn < 4
ORDER BY users_id, sent_at