Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBrandyn Lordi
17,778 PointsSolved 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:
Book Count
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
User Loans
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
1 Answer
Steven Parker
231,271 PointsYou 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.