How to count all books related to all authors ?

ahmed salah 3,216 Reputation points
2020-08-23T00:18:30.33+00:00

I work on SQL server 2012 I face issue I can't count books for all author
How to count book for all authors exist
this is my data

create table #books
(
BookId int,
BookName nvarchar(200),
AuthorId int
)
create table #Authors
(
AuthorId int,
AuthorName nvarchar(200)
)
insert into #Authors
values
(1,'Ahmed'),
(2,'Mohamed'),
(3,'Eslam')
insert into #books
values
(122,'c#',1),
(233,'Java',1),
(555,'c++',1),
(666,'photoshop',2),
(777,'asp.net',2),
(888,'python',2)

AuthorName countBooks
Ahmed 3
Mohamed 3
Eslam 0

Developer technologies | Transact-SQL
{count} votes

3 answers

Sort by: Most helpful
  1. Dan Guzman 9,406 Reputation points
    2020-08-23T01:03:06.833+00:00

    One way is with a LEFT JOIN, so that authors without books are included. Note that COUNT(b.BookId) will count only non-null BookId values for each author.

    SELECT
          a.AuthorName
        , COUNT(b.BookId) AS countOfBooks
    FROM #Authors AS a
    LEFT JOIN #Books AS b ON b.AuthorId = a.AuthorId
    GROUP BY a.AuthorName;
    
    1 person found this answer helpful.

  2. Jingyang Li 5,896 Reputation points Volunteer Moderator
    2020-08-23T02:45:24.317+00:00
    SELECT a.AuthorName
         ,Isnull(b.countOfBooks,0) countOfBooks
     FROM #Authors AS a
     LEFT JOIN (SELECT AuthorId, COUNT(BookId) AS countOfBooks 
     FROM #Books GROUP BY AuthorId) AS b ON b.AuthorId = a.AuthorId;
    
    0 comments No comments

  3. EchoLiu-MSFT 14,621 Reputation points
    2020-08-24T06:01:02.563+00:00

    Hi ahmedsalah,

    Please try:

       select a.AuthorName,count(b.AuthorId) countbooks  
        from #books b  
        right join #Authors a  
        on a.AuthorId=b.AuthorId  
        group by AuthorName  
        order by countbooks desc  
    
     
    

    19757-image.png

    If the response is helpful, please click "Accept Answer" and upvote it.

    Best Regards
    Echo

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.