Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
75 changes: 75 additions & 0 deletions lab_joins.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
USE sakila;

-- ## Challenge - Joining on multiple tables

-- Write SQL queries to perform the following tasks using the Sakila database:


-- 1. List the number of films per category.
SELECT c.name AS category, COUNT(*) FROM film f
JOIN film_category fc
ON f.film_id = fc.film_id
JOIN category c
ON c.category_id = fc.category_id
GROUP BY category;

-- 2. Retrieve the store ID, city, and country for each store.
SELECT s.store_id, c.city, co.country
FROM store s
JOIN address a ON s.address_id = a.address_id
JOIN city c ON a.city_id = c.city_id
JOIN country co ON c.country_id = co.country_id;


-- 3. Calculate the total revenue generated by each store in dollars.
SELECT s.store_id, SUM(p.amount) AS total_revenue
FROM store s
JOIN staff sf ON s.store_id = sf.store_id
JOIN payment p ON p.staff_id = sf.staff_id
GROUP BY s.store_id;


-- . Determine the average running time of films for each category.
SELECT c.name AS category, AVG(f.length) AS avg_running_time
FROM film f
JOIN film_category fc ON f.film_id = fc.film_id
JOIN category c ON fc.category_id = c.category_id
GROUP BY category;


-- **Bonus**:

-- 5. Identify the film categories with the longest average running time.,
SELECT c.name AS category, AVG(f.length) AS avg_running_time
FROM film f
JOIN film_category fc ON f.film_id = fc.film_id
JOIN category c ON fc.category_id = c.category_id
GROUP BY category
ORDER BY avg_running_time DESC;

-- 6. Display the top 10 most frequently rented movies in descending order.
SELECT f.title AS Movie, COUNT(*) AS rented_movies
FROM rental r
JOIN inventory i ON r.inventory_id = i.inventory_id
JOIN film f ON i.film_id = f.film_id
GROUP BY f.title, f.film_id
ORDER BY rented_movies DESC
LIMIT 10;

-- 7. Determine if "Academy Dinosaur" can be rented from Store 1.
SELECT title, f.film_id, store_id FROM film f
JOIN inventory i ON f.film_id = i.film_id
WHERE title = "Academy Dinosaur" AND store_id = 1;

-- 8. Provide a list of all distinct film titles, along with their availability status in the inventory.
-- Include a column indicating whether each title is 'Available' or 'NOT available.' Note that there are 42 titles
-- that are not in the inventory, and this information can be obtained using a `CASE` statement combined with `IFNULL`."
SELECT DISTINCT f.title,
CASE
WHEN i.film_id IS NULL THEN "Not_available"
ELSE "Avaialable"
END AS Availability_status
FROM film f
JOIN inventory i ON f.film_id = i.film_id
GROUP BY f.film_id, f.title;