问题
The question is
For each author, return the title and published_date of their first book. The result set should have five columns: author’s id, author’s name, book’s id, book’s title, and book’s published_date.
So I have the ouput columns I want except its displaying every book by each author with the required items, how do I get it to only show the book with the earliest published_date?
SELECT authors.id, authors.author, books.id, books.title, books.published_date
FROM authors
INNER JOIN books
ON authors.id = books.author_id
回答1:
One way of solving this is to use a query that fetches for each author the min publish date from the table books and then join it to the 2 tables:
select
a.id, a.author,
b.id, b.title, b.published_date
from authors a
inner join books b on b.author_id = a.id
inner join (
select author_id, min(published_date) published_date
from books
group by author_id
) g on g.author_id = b.author_id and g.published_date = b.published_date
回答2:
If using a recent version of sqlite (3.25 or newer), you can use window functions for a clean approach:
Given this sample database:
CREATE TABLE authors(id INTEGER PRIMARY KEY, author TEXT);
INSERT INTO authors VALUES (1, 'John Steinbeck'), (2, 'William Faulkner');
CREATE TABLE books(id INTEGER PRIMARY KEY
, author_id INTEGER REFERENCES authors(id)
, title TEXT, published_date TEXT);
INSERT INTO books(author_id, title, published_date) VALUES
(1, 'The Grapes Of Wrath', '1939-04-14'),
(2, 'As I Lay Dying', '1930-10-06'),
(2, 'The Sound And The Fury', '1929-10-07'),
(1, 'East Of Eden', '1952-09-19'),
(1, 'Tortilla Flat', '1935-01-01');
this query:
WITH ranked(author_id, author, book_id, title, published_date, published_order) AS
(SELECT a.id, a.author, b.id, b.title, b.published_date
, rank() OVER (PARTITION BY a.id ORDER BY b.published_date)
FROM authors AS a
JOIN books AS b ON a.id = b.author_id)
SELECT author_id, author, book_id, title, published_date
FROM ranked
WHERE published_order = 1
ORDER BY author_id;
will produce:
author_id author book_id title published_date
---------- -------------- ---------- ------------- --------------
1 John Steinbeck 5 Tortilla Flat 1935-01-01
2 William Faulkn 3 The Sound And 1929-10-07
For each author, it assigns a rank to each book in publication order (The rank() OVER (PARTITION BY a.id ORDER BY b.published_date)
column calculated in the CTE), and then selects only the books where that rank is 1 for the final results.
来源:https://stackoverflow.com/questions/56244360/how-to-return-first-book-published-by-each-author