diff --git a/lab-sql-joins-solved.sql b/lab-sql-joins-solved.sql new file mode 100644 index 0000000..05df48d --- /dev/null +++ b/lab-sql-joins-solved.sql @@ -0,0 +1,74 @@ +-- Write SQL queries to perform the following tasks using the Sakila database: +-- 1. List the number of films per category. +USE sakila; + +SELECT c.name AS category, COUNT(fc.film_id) AS number_of_films FROM sakila.category AS c +LEFT JOIN sakila.film_category AS fc +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 sakila.store AS s +LEFT JOIN sakila.address AS a +ON s.address_id = a.address_id +LEFT JOIN sakila.city AS c +ON a.city_id = c.city_id +LEFT JOIN sakila.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 , SUM(p.amount) AS total_revenue FROM sakila.payment AS p +JOIN sakila.staff AS s +ON p.staff_id = s.staff_id +JOIN sakila.store AS st +ON s.store_id = st.store_id +GROUP 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 average_running_time FROM sakila.film AS f +JOIN sakila.film_category AS fc +ON f.film_id = fc.film_id +JOIN sakila.category AS c +ON c.category_id = fc.category_id +GROUP BY c.name; + + +-- Bonus: +-- 5. Identify the film categories with the longest average running time. +SELECT c.name AS category, ROUND(AVG(f.length),2) AS average_running_time FROM sakila.film AS f +JOIN sakila.film_category AS fc +ON f.film_id = fc.film_id +JOIN sakila.category AS c +ON c.category_id = fc.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 sakila.film AS f +JOIN sakila.inventory AS i +ON f.film_id = i.film_id +JOIN sakila.rental AS r +ON i.inventory_id = r.inventory_id +GROUP BY f.title, f.film_id +ORDER BY times_rented DESC +LIMIT 10; + +-- 7. Determine if "Academy Dinosaur" can be rented from Store 1. +SELECT f.title, i.store_id, i.inventory_id FROM sakila.film AS f +JOIN sakila.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 f.title, + CASE + WHEN COUNT(i.inventory_id) = 0 THEN 'NOT available' + ELSE 'Available' + END AS availability_status +FROM sakila.film AS f +LEFT JOIN sakila.inventory AS i +ON f.film_id = i.film_id +GROUP BY f.film_id, f.title; \ No newline at end of file