2017-08-30 71 views
2

行我有一個查詢雲:限制3個%的用戶ID

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 

我要的是查詢返回的前3排的每個users.id,這可能嗎?

我沒有在stackoverflow或任何其他網站發現任何類似於這個問題。我很欣賞任何答案或有用的鏈接。由於

回答

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 
+0

謝謝@SqlZim!我知道答案會與Windows功能,但不知道如何做到這一點。 – Erick

+0

@Erick樂於幫忙! – SqlZim