Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Databases

Brandyn Lordi
Brandyn Lordi
17,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:

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
Steven Parker
216,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.