diff --git a/README.md b/README.md index c423128..8257781 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,7 @@ Useful for preparing for technical interviews and improving your SQL skills. - [2356. Number of Unique Subjects Taught by Each Teacher](./leetcode/easy/2356.%20Number%20of%20Unique%20Subjects%20Taught%20by%20Each%20Teacher.sql) - [3436. Find Valid Emails](./leetcode/easy/3436.%20Find%20Valid%20Emails.sql) - [3465. Find Products with Valid Serial Numbers](./leetcode/easy/3465.%20Find%20Products%20with%20Valid%20Serial%20Numbers.sql) + - [3570. Find Books with No Available Copies](./leetcode/easy/3570.%20Find%20Books%20with%20No%20Available%20Copies.sql) 2. [Medium](./leetcode/medium/) - [176. Second Highest Salary](./leetcode/medium/176.%20Second%20Highest%20Salary.sql) - [180. Consecutive Numbers](./leetcode/medium/180.%20Consecutive%20Numbers.sql) diff --git a/leetcode/easy/3570. Find Books with No Available Copies.sql b/leetcode/easy/3570. Find Books with No Available Copies.sql new file mode 100644 index 0000000..83b528b --- /dev/null +++ b/leetcode/easy/3570. Find Books with No Available Copies.sql @@ -0,0 +1,59 @@ +/* +Question 3570. Find Books with No Available Copies +Link: https://leetcode.com/problems/find-books-with-no-available-copies/description/?envType=problem-list-v2&envId=database + +Table: library_books + ++------------------+---------+ +| Column Name | Type | ++------------------+---------+ +| book_id | int | +| title | varchar | +| author | varchar | +| genre | varchar | +| publication_year | int | +| total_copies | int | ++------------------+---------+ +book_id is the unique identifier for this table. +Each row contains information about a book in the library, including the total number of copies owned by the library. +Table: borrowing_records + ++---------------+---------+ +| Column Name | Type | ++---------------+---------+ +| record_id | int | +| book_id | int | +| borrower_name | varchar | +| borrow_date | date | +| return_date | date | ++---------------+---------+ +record_id is the unique identifier for this table. +Each row represents a borrowing transaction and return_date is NULL if the book is currently borrowed and hasn't been returned yet. +Write a solution to find all books that are currently borrowed (not returned) and have zero copies available in the library. + +A book is considered currently borrowed if there exists a borrowing record with a NULL return_date +Return the result table ordered by current borrowers in descending order, then by book title in ascending order. +*/ + +WITH br AS ( + SELECT + book_id, + COUNT(book_id) AS current_borrowers + FROM borrowing_records + WHERE return_date IS NULL + GROUP BY book_id +) + +SELECT + lb.book_id, + lb.title, + lb.author, + lb.genre, + lb.publication_year, + br.current_borrowers +FROM library_books AS lb +INNER JOIN + br + ON lb.book_id = br.book_id +WHERE (lb.total_copies - br.current_borrowers) = 0 +ORDER BY br.current_borrowers DESC, lb.title ASC