Id user_id Name
--- -------- ------
1 1 A
2 1 B
3 1 C
4 2 D
5 2 E
6 2 F
这是我的用户表,我想使用user_id降序获取2行。 我想要类似的输出。
Id user_id Name
--- -------- ------
2 1 B
3 1 C
5 2 E
6 2 F
预先感谢
答案 0 :(得分:2)
使用row_number()
:
select Id, user_id, Name
from (select t.*, row_number() over (partition by user_id order by id desc) as seqnum
from t
) t
where seqnum <= 2
order by user_id, id
答案 1 :(得分:0)
我认为您严格需要ANCIer方法。您应该尝试下面的相关子查询-
SELECT Id, user_id, Name
FROM T T2
WHERE (SELECT COUNT(*)
FROM T T3
WHERE T2.user_id = T3.user_id
AND T2.Id <= T3.Id) <= 2