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 trialOmar David Laiton
1,005 PointsTrying to use LefT JOIN on 3 tables help please
I have 3 tables
"users"
3 columns User-ID int (11) Location varchar (250) Age int (11) Primary-key (User-ID)
"books"
5 columns ISBN varchar (13) Book-title varchar(255) Book-author varchar (255) Year-of-publication int(10) Publisher varchar (255)
"Book-raitings"
3 columns User-ID int (11) ISBN varchar (13) Book-rating int (11) Primary-key (user-id, ISBN)
The Location column varchar will be of format "city, state, country"
I have to generate top 10 books per each country into a separate table. Generate SQL dump.
Thank you for your help in advance.
1 Answer
Steven Parker
231,275 PointsThis is an unusual task because of needing to extract country from Location, and because you want to return the top 10 ranked titles per country. The methods for doing these kinds of things vary between databases, but here's how I might do this using ORACLE:
SELECT title, REGEXP_REPLACE(Location, '.*, ', '') AS Country
FROM books b
LEFT JOIN Book-ratings r on b.ISBN = r.ISBN
LEFT JOIN users u on u.User-ID = r.User-ID
WHERE ROW_NUMBER() OVER
(PARTITION BY REGEXP_REPLACE(Location, '.*, ', '') ORDER BY Book-rating) <= 10
ORDER BY Country
In an actual practice, I'd probably modify the users table by breaking Location apart into separate columns to make queries like this a lot easier to perform in the future.