如何通过order by子句按组选择第一行?

时间:2019-09-25 13:54:13

标签: sql oracle

我想按作者按销量最高的顺序选择销量最高的前三本书。从技术上讲,我想按每个有序组选择前3行。

这就是我现在拥有的:

    select 
        author_id
        ,book_id
        ,count(book_id) top
    from book_author
    group by author_id, book_id
    order by author_id, top

有什么解决方法吗?我在Google上搜索并找到了示例,但没有一个在使用order by

我希望已经很好地解释了我的问题。预先感谢。

1 个答案:

答案 0 :(得分:2)

我认为您想要汇总和row_number()

select author_id, book_id, cnt
from (select author_id, book_id, count(*) as cnt,
             row_number() over (partition by author_id order by count(*) desc) as seqnum
      from book_author ba
      group by author_id, book_id
     ) ba
where seqnum = 1
order by author_id, cnt desc;