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
WITH
clause, which is used to define two temporary tables (also known as Common Table Expressions or CTEs) -last_month_rentals
andthis_month_rentals
.last_month_rentals
CTE:- It selects distinct
customer_id
from therental
table. - It filters the records based on the
rental_date
column, considering only the rentals that happened last month.
- It selects distinct
this_month_rentals
CTE:- It also selects distinct
customer_id
from therental
table. - It filters the records based on the
rental_date
column, considering only the rentals that happened this month.
- It also selects distinct
The main
SELECT
statement retrieves all columns from thecustomer
table (usingc.*
).The query then joins the
customer
table (aliased asc
) with thelast_month_rentals
CTE (aliased aslmr
) on thecustomer_id
column. This means that it will only consider customers who rented items last month.The query also performs a
LEFT JOIN
with thethis_month_rentals
CTE (aliased astmr
) on thecustomer_id
column. 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
WHERE
clause filters the results to only include customers for whom thecustomer_id
in thethis_month_rentals
CTE 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