From 0ad0f881cd1574f2112e8dd0207c3fca398d9f41 Mon Sep 17 00:00:00 2001 From: GarriguesElena Date: Wed, 8 Jul 2026 15:53:46 +0200 Subject: [PATCH] sql_joins_lab_solved sql_joins_lab_solved --- SQL_joins_lab.sql | 82 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 SQL_joins_lab.sql diff --git a/SQL_joins_lab.sql b/SQL_joins_lab.sql new file mode 100644 index 0000000..0b3f7d2 --- /dev/null +++ b/SQL_joins_lab.sql @@ -0,0 +1,82 @@ +USE sakila; + +-- 1. List the number of films per category. +SELECT COUNT(f.film_id) AS number_of_films, c.name AS category +FROM film AS f +JOIN film_category AS fc +ON f.film_id = fc.film_id +JOIN category AS c +ON fc.category_id = c.category_id +GROUP BY c.name; + + +-- 2. Retrieve the store ID, city, and country for each store. +SELECT s.store_id AS store, c.city, co.country +FROM store AS s +JOIN address AS a +ON s.address_id = a.address_id +JOIN city as c +ON a.city_id = c.city_id +JOIN country AS co +ON c.country_id = co.country_id; + + +-- 3. Calculate the total revenue generated by each store in dollars. +SELECT s.store_id AS store, SUM(p.amount) AS total_revenue +FROM store AS s +JOIN staff AS st +ON s.store_id = st.store_id +JOIN payment AS p +ON st.staff_id = p.staff_id +GROUP BY store; + + +-- 4. Determine the average running time of films for each category. +SELECT ROUND(AVG(f.length), 2) AS average_running_time, c.name AS category +FROM film AS f +JOIN film_category AS fc +ON f.film_id = fc.film_id +JOIN category AS c +ON fc.category_id = c.category_id +GROUP BY c.name; + +-- 5. Identify the film categories with the longest average running time. +SELECT ROUND(AVG(f.length), 2) AS average_running_time, c.name AS category +FROM film AS f +JOIN film_category AS fc +ON f.film_id = fc.film_id +JOIN category AS c +ON fc.category_id = c.category_id +GROUP BY c.name +ORDER BY average_running_time DESC; + + +-- 6. Display the top 10 most frequently rented movies in descending order. +SELECT f.title AS movie, COUNT(r.rental_id) AS times_rented +FROM film AS f +JOIN inventory AS i +ON f.film_id = i.film_id +JOIN rental AS r +ON i.inventory_id = r.inventory_id +GROUP BY movie +ORDER BY times_rented DESC +LIMIT 10; + + +-- 7. Determine if "Academy Dinosaur" can be rented from Store 1. +SELECT f.title, i.store_id +FROM film AS f +JOIN inventory AS i +ON f.film_id = i.film_id +WHERE f.title = "Academy Dinosaur" AND i.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 IFNULL(i.inventory_id, 0) = 0 THEN "NOT available" + ELSE "Available" +END AS "Availability Status" +FROM film AS f +LEFT JOIN inventory AS i +ON f.film_id = i.film_id; +