diff --git a/lab-sql-joins.sql b/lab-sql-joins.sql new file mode 100644 index 0000000..a30aa9f --- /dev/null +++ b/lab-sql-joins.sql @@ -0,0 +1,107 @@ +USE sakila; + +-- 1. List the number of films per category. +SELECT * FROM film; +SELECT * FROM inventory; +SELECT * FROM film_category; + +SELECT + name, COUNT(film_id) AS category_count +FROM + film_category AS f + JOIN + category AS c ON f.category_id = c.category_id +GROUP BY name; + +-- 2. Retrieve the store ID, city, and country for each store. +SELECT + s.store_id, 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 + * +FROM + payment; + +SELECT + s.store_id, SUM(p.amount) AS total_revenue +FROM + store AS s + JOIN + customer AS C ON s.store_id = c.store_id + JOIN + payment AS p ON c.customer_id = p.customer_id +GROUP BY store_id; + +-- 4. Determine the average running time of films for each category. +SELECT + c.name, ROUND(AVG(f.length), 2) AS avg_film_length +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 name; + +-- 5. Identify the film categories with the longest average running time. +SELECT + c.name, ROUND(AVG(f.length), 2) AS avg_film_length +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 name +ORDER BY avg_film_length DESC +LIMIT 5; + +-- 6. Display the top 10 most frequently rented movies in descending order. +SELECT * FROM film; +SELECT * FROM rental; + +SELECT + f.title, COUNT(r.rental_id) AS rental_count +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 title +ORDER BY rental_count 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 + store_id = '1' + AND title = 'Academy Dinosaur'; + +-- 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 * from inventory; + +SELECT DISTINCT + (f.title), + CASE + WHEN i.film_id IS NULL THEN 'NOT Available' + ELSE 'Available' + END 'Availability' +FROM + film AS f + LEFT JOIN + inventory AS i ON f.film_id = i.film_id;