Im currently working on the second part of a two part exercise and am having trouble figuring out how to show the average number of films per state from a dvd rentals database. The question I am trying to address is:
For each US state, show the average number of G-rated films that each customer has rented, in descending order. You only should provide one value for each state.
I currently have
WITH cte AS
(
SELECT COUNT(DISTINCT(rental_id)) AS filmcount
FROM rental
)
SELECT DISTINCT(district), AVG(filmcount) AS avg_film /*COUNT(DISTINCT(rental_id)) */
FROM cte, customer
LEFT OUTER JOIN address
ON customer.address_id = address.address_id /*Using parent keys to join with foreign keys from relevant tables. we are focusing on customer rentals so this is our starting basis*/
LEFT OUTER JOIN rental
ON customer.customer_id = rental.customer_id
LEFT OUTER JOIN inventory
ON rental.inventory_id = inventory.inventory_id
LEFT OUTER JOIN film
ON inventory.film_id = film.film_id
LEFT OUTER JOIN city
ON address.city_id = city.city_id
WHERE return_date IS NOT NULL
AND rating = 'G'
AND country_id = 103
GROUP BY district;
with my results being enter image description here This is the before table enter image description here
Customer | Address | Rental | Inventory |
---|---|---|---|
customer_id | address_id | rental_id | inventory_id |
store_id | address | rental_date | film_id |
first_name | address2 | inventory_id | store_id |
last_name | district | customer_id | last_update |
city_id | return_date | ||
address_id | postal_code | staff_id | |
activebool | phone | last_update | |
create_date | last_update | ||
last_update | |||
active |
Film | City |
---|---|
film_id | city_id |
title | city |
description | country_id |
release_year | last_update |
language_id | |
original_language_id | |
rental_duration | |
rental_rate | |
length | |
replacement_cost | |
rating | |
last_update | |
special_features | |
fulltext |
How can I get the average count of unique ID per state or in this case district? Please help :)