我有两张桌子:
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
BOOK_CODE BRANCH_NUM ON_HAND
--------- ---------- -------
0189 1 2
0189 2 2
0200 1 11
6128 3 7
我想要显示每本书的标题,book_code和可用副本总数。
我可以单独进行...我可以用以下内容获取每本书和book_code的编号:
SELECT inventory.book_code,
SUM(on_hand)
FROM inventory
GROUP BY inventory.book_code;
但是如何在这些结果旁边显示标题?我尝试使用join并尝试在初始select语句中选择它,但我得到一个“不是GROUP BY表达式”错误。
答案 0 :(得分:3)
使用派生表获取总和 - 此示例使用OUTER连接,以防您想要查看没有任何INVENTORY
记录的书籍:
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
否则,您可以使用INNER联接。
答案 1 :(得分:2)
只需将join
两个表放在一起,然后更新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 :(得分: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