[英]How to select nth row of each group in SQL
I have a table like this我有一张这样的桌子
member_id会员ID | book_title书名 |
---|---|
1 1 | one-one一一 |
1 1 | one-two一二 |
1 1 | one-three一三 |
2 2 | two-one二合一 |
2 2 | two-two二二 |
2 2 | two-three二三 |
I want to group by member_id
and 3rd book title, so if I run the query, the result must be:我想按member_id
和第三本书名进行分组,所以如果我运行查询,结果必须是:
member_id会员ID | book_title书名 |
---|---|
1 1 | one-three一三 |
2 2 | two-three二三 |
Assuming with "3rd book title" you mean " the third book if sorted alphabetically by title " this can be achieved using window functions:假设使用“第三本书标题”,您的意思是“如果按标题字母顺序排序的第三本书”,这可以使用窗口函数来实现:
select member_id, book_title
from (
select member_id, book_title,
row_number() over (partition by member_id order by book_title) as rn
from the_table
) t
where rn = 3;
Note that this won't return members that have less than 3 books assigned.请注意,这不会返回分配了少于 3 本书的成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.