Welcome to the Treehouse Community
Looking to learn something new?
Brandyn Lordi17,776 Points
Solved but... Are these challenges possible without derived tables?
I was able to solve both challenges with the use of derived tables, but i'm curious to know if maybe i'm missing something as the title states?
My code for reference:
SELECT bn.title, count(all_books.title) as book_count FROM books_north as bn INNER JOIN( SELECT title FROM books_north UNION ALL SELECT title from books_south ) as all_books on bn.title = all_books.title group by all_books.title
SELECT p.first_name, p.email, count(loans.patron_id),loans.patron_id FROM patrons as p INNER JOIN ( select patron_id from loans_north where returned_on IS NULL UNION ALL select patron_id from loans_south where returned_on IS NULL ) as loans ON loans.patron_id = p.id group by first_name
Steven Parker216,135 Points
You didn't mention what the objective was for each SQL sample, but if the first one is intended to list all titles of both locations with total quantity, that code won't produce it. But you can get a correct count and also simplify the query a bit this way:
SELECT title, COUNT(1) AS book_count FROM ( SELECT title FROM books_north UNION ALL SELECT title FROM books_south ) GROUP BY title
And would a CTE count as an alternative to the derived table?
WITH all_books AS ( SELECT title FROM books_north UNION ALL SELECT title FROM books_south ) SELECT title, COUNT(1) AS book_count FROM all_books GROUP BY title
But I think you need one or the other because of applying the aggregate to the set combination.