2012-02-08 78 views
0

我有一個具有以下結構的數據庫。每本書可以有多個作者,每個作者可以寫多本書。如何在MS Access中使用多對多關係進行計算

[book:book_id, book_name, book_price] 
[author: author_id, author_name] 
[link:book_id, author_id] 

{book_id's和author_id的鏈接。整個結構如下所示:http://i.stack.imgur.com/vIFNU.png}

現在每本書都有一個價格(貨幣)。價格的30%應平均分配給每位爲本書作出貢獻的作者。 我的問題是如何找到每個作者在特定年份的總付款。

[我想到了一個解決方案,我的自我。我所能做的最多隻有1步。如果您可以提供我一些提示或材料在哪裏可以找到如何做這樣的操作,這將是非常有益]

我的解決方案的算法是:

  1. 因此,對於每個book_id,我需要找到具有相同book_id的中間表中author_id的數量。 (可以通過查詢做)

  2. 如果我通過number_of_author_in_book劃分book_price與30/100乘它,我得到了那本書會去每個作者的賬戶那本書(比如payment_of_one_author_in_book)錢

  3. 對於中間表中的每個author_id,我查找相應的book_id,並將author_id的payment_of_one_author_in_book添加到與作者ID對應的新變量(author_payment_this_year)中,如果年份與查詢年份匹配。

在此先感謝

回答

0
SELECT author.AuthorId, author.Author_name, book.Book_Name, book.Book_Price, [Book_Price]/DCount("[Author_id]","[Link]","[Book_id]=" & [Book_Id]) AS Share 
FROM (author INNER JOIN link AS link_1 ON author.AuthorId = link_1.Author_id) INNER JOIN book ON link_1.Book_id = book.Book_Id; 

基本上,它只是加入了三個表。唯一棘手的問題是使用DCount函數來合計鏈接中有多少位作者共享此書_ID

1

此示例包含別名和子查詢。

SELECT 
    a.author_id, 
    a.author_name, 
    SUM(share.auth_share) AS author_total 
FROM (link l 
INNER JOIN (
    SELECT 
     b.book_id, 
     ([b.book_price] * 0.3)/[no_auth] AS auth_share 
    FROM book b 
    INNER JOIN (
     SELECT 
      l.book_id, 
      COUNT(l.author_id) AS no_auth 
     FROM link l 
     GROUP BY l.book_id) AS ac 
    ON b.book_id = ac.book_id) AS share 
ON l.book_id = share.book_id) 
INNER JOIN author a 
ON l.author_id = a.author_id 
GROUP BY a.author_id,a.author_name 
相關問題