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;

Here is the formatted SQL statement using PostgreSQL syntax:

            
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;

This SQL statement is using Common Table Expressions (CTEs) to create two temporary views: last_month_rentals and this_month_rentals. It then selects all columns from the customer table where the customer_id is in last_month_rentals but not in this_month_rentals.

  • Public
  • ·
  • Mon, 17 Jul 2023 11:53:01 GMT