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
80 changes: 80 additions & 0 deletions joins.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#1 List the number of films per category.
USE sakila;

SELECT c.name, COUNT(*)
FROM category c
LEFT JOIN film_category fc
ON c.category_id = fc.category_id
GROUP BY c.name;

#2 Retrieve the store ID, city, and country for each store.

SELECT store_id, city, country
FROM store s
LEFT JOIN address a
ON s.address_id = a.address_id
LEFT JOIN city c
ON a.city_id = c.city_id
LEFT 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)
FROM payment p
LEFT JOIN staff s
ON p.staff_id = s.staff_id
LEFT JOIN store 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, AVG(f.length)
FROM film f
LEFT JOIN film_category fc
ON f.film_id = fc.film_id
LEFT JOIN category c
ON fc.category_id = c.category_id
GROUP BY c.name
;
#Bonus:
#Identify the film categories with the longest average running time.
SELECT c.name, AVG(f.length)
FROM film f
LEFT JOIN film_category fc
ON f.film_id = fc.film_id
LEFT JOIN category c
ON fc.category_id = c.category_id
GROUP BY c.name
ORDER BY AVG(f.length) DESC
LIMIT 3
;
#Display the top 10 most frequently rented movies in descending order.
SELECT f.title, count(*)
FROM rental r
LEFT JOIN inventory i
ON r.inventory_id = i.inventory_id
LEFT JOIN film f
ON i.film_id = f.film_id
GROUP BY f.title
ORDER BY count(*) DESC
LIMIT 10;

#Determine if "Academy Dinosaur" can be rented from Store 1.

SELECT *
FROM film f
LEFT JOIN inventory i
ON f.film_id = i.film_id
WHERE f.title = "Academy Dinosaur" AND i.store_id = 1;

#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 NOT NULL THEN "Available"
ELSE "Not Available"
END AS Availability
FROM film f
LEFT JOIN inventory i
ON f.film_id = i.film_id;