WITH last_month_rentals AS ( SELECT DISTINCT customer_id FROM rental WHERE rental_date >= date_trunc ('month', current_date - interval '1 month') AND rental_date < date_trunc ('month', current_date) ), this_month_rentals AS ( SELECT DISTINCT customer_id FROM rental WHERE rental_date >= date_trunc ('month', current_date) AND rental_date < date_trunc ('month', current_date + interval '1 month') ) SELECT c.* FROM customer c JOIN last_month_rentals lmr ON c.customer_id = lmr.customer_id LEFT JOIN this_month_rentals tmr ON c.customer_id = tmr.customer_id WHERE tmr.customer_id IS NULL;
The given SQL statement is a PostgreSQL query that retrieves a list of customers who rented items last month but have not rented anything this month. Here's a breakdown of the query:
The query starts with a
WITHclause, which is used to define two temporary tables (also known as Common Table Expressions or CTEs) -last_month_rentalsandthis_month_rentals.last_month_rentalsCTE:- It selects distinct
customer_idfrom therentaltable. - It filters the records based on the
rental_datecolumn, considering only the rentals that happened last month.
- It selects distinct
this_month_rentalsCTE:- It also selects distinct
customer_idfrom therentaltable. - It filters the records based on the
rental_datecolumn, considering only the rentals that happened this month.
- It also selects distinct
The main
SELECTstatement retrieves all columns from thecustomertable (usingc.*).The query then joins the
customertable (aliased asc) with thelast_month_rentalsCTE (aliased aslmr) on thecustomer_idcolumn. This means that it will only consider customers who rented items last month.The query also performs a
LEFT JOINwith thethis_month_rentalsCTE (aliased astmr) on thecustomer_idcolumn. This means that it will include all customers who rented items last month, regardless of whether they rented items this month or not.Finally, the
WHEREclause filters the results to only include customers for whom thecustomer_idin thethis_month_rentalsCTE isNULL. This means that the final result will only include customers who rented items last month but have not rented anything this month.
- Public
- ·
- Tue, 27 Jun 2023 09:23:46 GMT