Instagram
youtube
Facebook
Twitter

Show LEAD() and LAG() for Customer Payments

Show LEAD() and LAG() for Customer Payments

Payments Table:


Query Explanation:

  • LAG(Amount) gets the previous payment amount for the same customer.

  • LEAD(Amount) gets the next payment amount for the same customer.

  • PARTITION BY CustomerID ensures that the window functions operate within each customer group.

  • ORDER BY PaymentDate ensures payments are compared in chronological order.


SQLQuery:

SELECT 
    CustomerID,
    PaymentID,
    Amount,
    PaymentDate,
    LAG(Amount) OVER (PARTITION BY CustomerID ORDER BY PaymentDate) AS PreviousPayment,
    LEAD(Amount) OVER (PARTITION BY CustomerID ORDER BY PaymentDate) AS NextPayment
FROM 
    Payments;


Output: