技术问询:编写SQL查询年出版量超1的作者年度出书数量(用MediaCode)
Solution
Here's the SQL query that meets all your requirements:
SELECT i.Author, i.PubYear AS Pubyear, COUNT(i.ItemID) AS "Total Book Published in Year" FROM Item i INNER JOIN Media m ON i.MediaID = m.MediaID WHERE m.MediaCode IS NOT NULL GROUP BY i.Author, i.PubYear HAVING COUNT(i.ItemID) > 1 ORDER BY i.Author, i.PubYear;
Explanation
Let's break down how this query works:
- Table Join: We use an
INNER JOINbetween theItemandMediatables to link each book to its media type. This lets us useMediaCode(as required) instead of relying solely onMediaID. TheWHEREclause ensures we only include items with valid media codes. - Grouping & Counting: We group results by
AuthorandPubYearto calculate how many books each author published per year.COUNT(i.ItemID)counts individual book items (like physical copies). If you want to count distinct book titles instead, swap this withCOUNT(DISTINCT i.Title). - Filtering: The
HAVINGclause removes any author-year pairs where fewer than 2 books were published, which aligns with your requirement. - Column Alignment: We alias
PubYeartoPubyearto match your requested column name, and use a quoted alias for the count column to preserve the exact wording you specified. - Readability: The
ORDER BYclause sorts results by author and publication year for easier scanning.
Quick Notes
- The join using
MediaIDis only necessary to accessMediaCode—we don't useMediaIDelsewhere in the query, which adheres to your constraint. - Adjust the count function based on whether you need to count individual copies or unique book titles.
内容的提问来源于stack exchange,提问作者Joseph Robson
相关产品推荐
相关产品推荐

