[英]Return Authors by latest published book + Authors with no published books
I have two tables : 我有两个表:
•Table 1: Books
•表1: Books
•Table 2: Authors
•表2: Authors
I have the following query:(This query returns all authors with book title and date published) 我有以下查询:(此查询返回具有书名和出版日期的所有作者)
SELECT Authors.AuthorName, Books.BookTitle, Books.DatePublished, Books.Author
FROM Authors LEFT OUTER JOIN Books ON Authors.AuthorID = Books.Author
Problem:!! 问题:!!
I would like to return all Authors(Both who have books published . and those that dont have books published. 我想归还所有作者(既有出版过的书籍,也有没有出版过的书籍。
Condition (The authors that do have books. return only the latest published book) 条件(拥有书籍的作者。仅返回最新出版的书籍)
I am able to get latest published book with the below query: 我可以通过以下查询获取最新出版的书:
SELECT a.*
FROM [Books] a left outer join Books b on a.Author = b.author and
a.DatePublished < b.DatePublished where b.ISDN is null
Question: How can i incorporate both these queries to return ALL the authors + authors with latest published book ? 问题:如何合并这两个查询,以返回所有作者+最新出版的书的作者?
Please try: 请试试:
SELECT DISTINCT
AuthorName,
BookTitle,
DatePublished,
Author
FROM(
SELECT
Authors.AuthorName,
Books.BookTitle,
Books.DatePublished,
Books.Author,
ROW_NUMBER() over (partition by Authors.AuthorID order by DatePublished desc) Rnum
FROM Authors LEFT OUTER JOIN Books ON Authors.AuthorID = Books.Author
)x WHERE Rnum=1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.