在两个一对多表之间加入

时间:2017-06-02 09:11:24

标签: sql ms-access

我有这两个表,我必须编写这个SQL查询(Microsoft Access):

  • 为每个出售任何图书的作者撰写一个查询,显示他们销售了多少图书(book_id)和多少单位(订购数量)

enter image description here

我已尝试使用此查询,但它无法正常工作

SELECT authors.author_id, Count(orders.book_id) AS CountOfbook_id,
Sum(orders.quantity_ordered) AS SumOfquantity_ordered
FROM authors 
LEFT JOIN orders ON authors.book_id = orders.book_id
GROUP BY authors.author_id;

但它不起作用,因为它重复了同一本书从customersOrders enter image description here

获得的许多次

1 个答案:

答案 0 :(得分:1)

这个怎么样?

select author,sum(CountOfbook_id), sum(SumOfquantity_ordered)
from (
    SELECT authors.author_id as author, Count(orders.book_id) AS CountOfbook_id,
    Sum(orders.quantity_ordered) AS SumOfquantity_ordered
    FROM authors 
    LEFT JOIN orders ON authors.book_id = orders.book_id
    GROUP BY authors.author_id,authors.book_id;)
group by author;