2017-06-02 123 views
-1

我有這兩個表,我必須寫這個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

+0

那麼你試過了什麼?它產生了什麼結果/它與你想要的有什麼不同? –

+0

請閱讀http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557和接受的答案 –

+0

我寫了查詢我試過底部 – sparkle

回答

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; 
+0

我試過了,但是我得到了兩次相同的作者,請看:https://d2ppvlu71ri8gs.cloudfront.net/items/3W2B1G2t232C1p0i3J3f/Image%202017-06-02 %20at%2011.51.59%20 AM.png?v = 59ceaca9 – sparkle

+0

我修改了它 – nacho