Skip to content
Open
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
103 changes: 103 additions & 0 deletions joins.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
USE sakila;

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

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

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

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

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

-- Bonus 2: Display the top 10 most frequently rented movies in descending order
SELECT
f.title,
COUNT(r.rental_id) AS times_rented
FROM film f
JOIN inventory i
ON f.film_id = i.film_id
JOIN rental r
ON i.inventory_id = r.inventory_id
GROUP BY f.film_id, f.title
ORDER BY times_rented DESC, f.title ASC
LIMIT 10;

-- Bonus 3: Determine if 'Academy Dinosaur' can be rented from Store 1
SELECT
f.title,
i.store_id,
CASE
WHEN COUNT(i.inventory_id) > 0 THEN 'Yes'
ELSE 'No'
END AS can_be_rented
FROM film f
LEFT JOIN inventory i
ON f.film_id = i.film_id
AND i.store_id = 1
WHERE f.title = 'Academy Dinosaur'
GROUP BY f.title, i.store_id;

-- Bonus 4: List all distinct film titles with availability status in inventory
SELECT
f.title,
CASE
WHEN COUNT(i.inventory_id) > 0 THEN 'Available'
ELSE 'NOT available'
END AS availability_status
FROM film f
LEFT JOIN inventory i
ON f.film_id = i.film_id
GROUP BY f.film_id, f.title
ORDER BY f.title;