Quantcast
Channel: Active questions tagged cte - Database Administrators Stack Exchange
Viewing all articles
Browse latest Browse all 216

List Top Daily Rentals Per Customer using a CTE

$
0
0

I've been trying to learn CTEs and having a bit or trouble getting the hang of them. I wrote a query against the Sakila Sample database that lists information about horror movie rentals for each day.

Here is the overblown (and redundant) SQL that I came up with:

SELECT CONCAT(CU.last_name, ', ', CU.first_name) AS customer,        A.phone,         F.title,         date(R.rental_date) AS rental_date FROM sakila.rental R      LEFT JOIN sakila.inventory I ON R.inventory_id = I.inventory_id      LEFT JOIN sakila.film F ON I.film_id = F.film_id      LEFT JOIN sakila.film_category FC on F.film_id = FC.film_id     LEFT JOIN sakila.category C ON FC.category_id = C.category_id      LEFT JOIN sakila.customer CU ON R.customer_id = CU.customer_id     LEFT JOIN sakila.address A ON CU.address_id = A.address_id WHERE CU.customer_id in        (SELECT CU.customer_id        FROM rental R        LEFT JOIN sakila.customer CU ON R.customer_id = CU.customer_id        LEFT JOIN sakila.inventory I ON R.inventory_id = I.inventory_id         LEFT JOIN sakila.film F ON I.film_id = F.film_id         LEFT JOIN sakila.film_category FC on F.film_id = FC.film_id        LEFT JOIN sakila.category C ON FC.category_id = C.category_id         WHERE C.name = "Horror"        GROUP BY CU.customer_id        HAVING COUNT(CU.customer_id) >= 3) AND C.name = "Horror" ORDER BY customer, title, rental_date DESC;

And here are some of the results in my database client (Navicat for MySQL):

Daily Horror Movie Rentals Query in Navicat for MySQL

Is there a way to rewrite the query using a CTE?

It seems like just the type of query that a CTE would be perfect for, if only I could figure it out!

Thanks!


Viewing all articles
Browse latest Browse all 216

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>