SQLAI.ai

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:

  1. 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 and this_month_rentals.

  2. last_month_rentals CTE:

    • It selects distinct customer_id from the rental table.
    • It filters the records based on the rental_date column, considering only the rentals that happened last month.
  3. this_month_rentals CTE:

    • It also selects distinct customer_id from the rental table.
    • It filters the records based on the rental_date column, considering only the rentals that happened this month.
  4. The main SELECT statement retrieves all columns from the customer table (using c.*).

  5. The query then joins the customer table (aliased as c) with the last_month_rentals CTE (aliased as lmr) on the customer_id column. This means that it will only consider customers who rented items last month.

  6. The query also performs a LEFT JOIN with the this_month_rentals CTE (aliased as tmr) on the customer_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.

  7. Finally, the WHERE clause filters the results to only include customers for whom the customer_id in the this_month_rentals CTE is NULL. 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