0

I have two tables:

BOOK

BOOK_CODE   TITLE   PUBLISHER_CODE   TYPE   PRICE   PAPERBACK
---------   -----   --------------   ----   -----   ---------
  0189      Magic        FA          HOR    7.99      Yes
  0378     Venice        FA          ART    24.50     No
  0808    The Edge       JP          MYS    6.99      Yes
  6128      Jazz         PL          FIC    12.99     Yes
  0200      Start        HQ          FIC    8.99      Yes

INVENTORY

BOOK_CODE   BRANCH_NUM     ON_HAND
---------   ----------     -------
  0189           1            2
  0189           2            2
  0200           1           11
  6128           3            7

I was wanting to display the title, book_code and the total number of copies available for each book.

I can do them separately... I can get the number of each book and the book_code with:

  SELECT inventory.book_code,
         SUM(on_hand)
    FROM inventory
GROUP BY inventory.book_code;

But how do I get the title to display next to these results? I tried using join and tried selecting it in the initial select statement but I get a "not a GROUP BY expression" error.

3 Answers 3

3

Use a derived table to get the sum - this example uses an OUTER join in case you want to see books without any INVENTORY records:

   SELECT b.title,
          b.book_code,
          COALESCE(x.numOnHand, 0)
     FROM BOOK b
LEFT JOIN (SELECT i.book_code,
                  SUM(on_hand) AS numOnHand
             FROM INVENTORY i
         GROUP BY i.book_code) x ON x.book_code = b.book_code

Otherwise, you can use an INNER join.

0
2

Simply join the two tables together and then update your group by.

SELECT i.book_code, b.title, SUM(i.on_hand)
FROM inventory i
    LEFT JOIN book b on b.book_code = i.book_code
GROUP BY i.book_code, b.title;
2
select b.title, b.book_code, sum(i.on_hand) as total_copy
from inventroy i, book b
where i.book_code = b.book_code
group by i.book_code, b.title

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.