79. Spend difference between the last and the second last rentals

hard

************
  • ***********************************************************************************************************************************
  • *************************************.
  • ************************************************
****
  • ********************************************************

Table: payment

Movie rental payment transactions table

   col_name   | col_type
--------------+--------------------------
 payment_id   | integer
 customer_id  | smallint
 staff_id     | smallint
 rental_id    | integer
 amount       | numeric
 payment_ts   | timestamp with time zone

Sample results

 customer_id | delta
-------------+-------
           1 |  3.00
           2 |  0.00
           3 |  2.00
           4 | -1.00
           5 | -2.00

Solution postgres

WITH cust_spend_seq AS (
	SELECT 
	  customer_id,
	  payment_ts,
	  amount AS current_payment,
	  LAG(amount, 1) OVER(PARTITION BY customer_id ORDER BY payment_ts) AS prev_payment,
	  ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY payment_ts DESC) AS payment_idx
	FROM payment P
)
SELECT
    customer_id,
    current_payment - prev_payment AS delta
FROM cust_spend_seq
WHERE customer_id IN(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
AND payment_idx = 1;
    

Explanation

This query calculates the difference in payment amounts (delta) between the current payment and the previous payment for each customer in a list of ten specified customer IDs. It does this by using a common table expression (CTE) called "cust_spend_seq" that selects the customer ID, payment timestamp, and amount for each payment in the "payment" table, and also calculates the previous payment amount using the LAG function and the payment index using the ROW_NUMBER function.

The main query then selects only the customer ID and delta columns from the CTE for the specified customer IDs and for the most recent payment (i.e. where the payment index is 1). This can be useful for analyzing customer spending patterns and identifying any significant changes in spending behavior between consecutive payments.

Expected results



More LAG, LEAD questions

ID Title Level FTPR
199 Students improvement snap hard
67%
195 MoM user growth snap hard
14%
180 Members moved from Microsoft to Google directly. linkedin hard
21%
147 2 days streak customers google hard
13%
121 Week over week change of first ever bookings airbnb hard
14%
114 Dod revenue change rate amazon easy
15%
80 DoD revenue growth for each store hard
19%
69 Number of happy customers hard
7%
68 Spend difference between first and second rentals hard
12%