Please help me with retrieve max values. I've created a few simple tables. The first one is users the second one is books. So i need to use sub query to retrieve the the names of the books which date of taking by user is the latest
Here are the tables:
CREATE TABLE book_base
(
book_id int,
user_id int,
title VARCHAR(20),
date DATE,
);
CREATE TABLE users
(
userid int,
name VARCHAR(20),
);
INSERT INTO book_base (book_id, user_id, title, date)
VALUES ('221', 1, 'Just book', '2021-2-2'),
('222', 1, 'The book', '2020-4-8'),
('223', 1, 'My book', '2019-8-8'),
('228', 2, 'Nice book', '2021-1-2'),
('225', 2, 'Coole book', '2020-4-8'),
('226', 2, 'Super book', '2019-9-8');
INSERT INTO users (userid, name)
VALUES ('1', 'John Smith'),
('2', 'Mary Adams');
And I've tried to do like this
SELECT
userid AS [UID],
name AS [UserName],
bb.title, bb.date
FROM
users u
JOIN
(SELECT user_id title, MAX(date)
FROM book_base) bb ON u.userid = bb.user_id
The result should be just the rows there date is max date