Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is wrong with my "group by" code in SQL?

FEEDBACK table:

CREATE TABLE Feedback 
(
    FeedbackID nvarchar(50) NOT NULL PRIMARY KEY, 
    Rating SMALLINT, 
    Comments nvarchar(50), 
    MemberID nvarchar(50) FOREIGN KEY REFERENCES Member(MemberID), 
    BookID NVARCHAR(50) FOREIGN KEY REFERENCES Book(BookID)
); 

BOOK table:

CREATE TABLE Book  
(
    BookID nvarchar(50) NOT NULL PRIMARY KEY, 
    Name nvarchar(50), 
    SerialNumber nvarchar(50), 
    CategoryID nvarchar(50) FOREIGN KEY REFERENCES Category(CategoryID), 
    PublisherID NVARCHAR(50) FOREIGN KEY REFERENCES Publisher(PublisherID), 
    Unit_Price nvarchar(50), 
    Quantity NVARCHAR (50)
); 

I have only managed to get this by using

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT BookID, COUNT(FeedbackID) AS Numoffeedback 
FROM Feedback 
GROUP BY BookID;

BookID | TotalNumberofFeedbacks
-------+-----------------------

But my desired output is this :

BookID | Name | TotalNumberofFeedbacks
-------+------+-----------------------

I tried do this

SELECT BookID, COUNT(FeedbackID) AS Numoffeedback 
FROM Feedback 
GROUP BY BookID, Name; 

but i received this error "Invalid column name ‘Name’.

>Solution :

You need to join the two tables together and then aggregate by book. You may try the following query:

SELECT b.BookID, b.Name, COUNT(f.BookID) AS TotalNumberOfFeedbacks
FROM Book b
LEFT JOIN Feedback f
    ON f.BookID = b.BookID
GROUP BY b.BookID, b.Name;

Note that we count f.BookID here. The reason for this is should a certain book have no feedback, we want the count to be zero.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading