How to select the first N rows of each group?

后端 未结 3 677
旧时难觅i
旧时难觅i 2020-12-01 07:52

I have two SQLite tables like this:

 AuthorId | AuthorName
----------------------
 1        | Alice
 2        | Bob
 3        | Carol
 ...      | ....


 Boo         


        
相关标签:
3条回答
  • 2020-12-01 08:32

    There is alternative variant:

    SELECT * FROM (
        SELECT * FROM BOOK, AUTHOR
        WHERE BOOK.AUTHORID = AUTHOR.AUTHORID
    ) T1
    WHERE T1.BOOKID IN (
        SELECT T2.BOOKID FROM BOOK T2
        WHERE T2.AUTHORID = T1.AUTHORID
        ORDER BY T2.BOOKTITLE
        LIMIT 2
    )
    ORDER BY T1.BOOKTITLE
    
    0 讨论(0)
  • 2020-12-01 08:36

    You can do the counting using a correlated subquery:

    SELECT b.BookId, a.AuthorId, a.AuthorName, b.Title
    FROM Author a join
         Book b
         on a.AuthorId = b.AuthorId
    where (select count(*)
           from book b2
           where b2.bookId <= b.BookId and b2.AuthorId = b.AuthorId
          ) <= 2;
    

    For a small database this should be fine. If you create a composite index on Book(AuthorId, BookId) then that will help the query.

    0 讨论(0)
  • 2020-12-01 08:51

    Here you go. Might be too late but I just saw the post. You can change the <=2 to match the n you need.

    SELECT 
     a.authorid,
     a.authorname,
     b.bookid,
     b.booktitle
    FROM author a
    JOIN book b ON b.authorid = b.authorid
    QUALIFY ROW_NUMBER() OVER (PARTITION BY a.authorid
    ORDER BY   b.booktitle ASC) <=2
    
    0 讨论(0)
提交回复
热议问题