Count number of Rows with the same value in a Column

15,987

Try this one but please take note that I converted the author_id from varchar to int):

SELECT book_count,a.author_id,a.fn, a.ln 
FROM author a
JOIN
(
  SELECT c.author_id,COUNT(*) book_count FROM book c
  GROUP BY c.author_id
) b 
ON a.author_id = b.author_id
ORDER BY book_count DESC LIMIT 1

Here's the SQLFiddle.

Share:
15,987

Related videos on Youtube

Erkyy
Author by

Erkyy

Some cannot C because they cannot C#

Updated on October 09, 2022

Comments

  • Erkyy
    Erkyy over 1 year

    I have these two entity with their attributes:

    book - book_id, book_name, author_id, editor_id, subject_id, isbn

    author - author_id, fn, ln

    I have to query the author with the most number of rows here's the attributes and entity:

    | book_id | book_name   | author_id |  editor_id |  isbn     |
    --------------------------------------------------------------
    |       1 | Book1 Title |  Author1  |  Editor1   | 8000-9000 |
    |       2 | Book2 Title |  Author2  |  Editor1   | 8000-9001 |
    |       1 | Book1 Title |  Author1  |  Editor1   | 8000-9002 |
    |       3 | Book2 Title |  Author2  |  Editor1   | 8000-9003 |
    
    | author_id |  fn    |    ln    |
    ---------------------------------
    |       1   | name1  |  lname1  |
    |       2   | name2  |  lname2  |
    |       3   | name3  |  lname3  | 
    

    and here is my code:

    SELECT author.author_id, author.fn, author.ln, COUNT(DISTINCT book.editor_id) as num
    FROM `editor`, `book`
    GROUP BY `editor_id`
    LIMIT 0,1
    

    but off-course i don't get what I want. The output must be:

    | author_id |  fn    |    ln    |
    ---------------------------------
    |       1   | name1  |  lname1  |
    

    since the "author_id = 1" has 2 entries on books.