我有一个具有以下结构的数据库。每本书可以有多位作者,每位作者可以写多本书。
[book:book_id, book_name, book_price]
[author: author_id, author_name]
[link:book_id, author_id]
{book_id' s和author_id' s已关联。完整的结构如下所示:http://i.stack.imgur.com/vIFNU.png}
现在每本书都有一个价格(货币)。价格的30%应平均分配给每位为本书做出贡献的作者。 我的问题是如何查找特定年份每位作者的总付款。
[我想到了一个解决方案。我只能做到第1步。如果你能给我一些提示或材料,我可以找到这样的操作,这将是非常有帮助的]
我的解决方案的算法是:
因此,对于每个book_id,我需要找到中间表中具有相同book_id的author_id的数量。 (可以通过查询来完成)
如果我通过number_of_author_in_book划分book_price与30/100乘它,我得到了那本书会去每个作者&#39钱的帐户的那本书(说payment_of_one_author_in_book)
有关在中间表中的每个AUTHOR_ID,我查找用于相应book_id和该AUTHOR_ID添加payment_of_one_author_in_book到对应于作者ID一个新的变量(author_payment_this_year),如果年匹配到查询年。
提前致谢
答案 0 :(得分: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
答案 1 :(得分: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函数来累计链接中有多少作者共享此book_ID