Welcome Back

Google icon Sign in with Google
OR
I agree to abide by Pharmadaily Terms of Service and its Privacy Policy

Create Account

Google icon Sign up with Google
OR
By signing up, you agree to our Terms of Service and Privacy Policy
Instagram
youtube
Facebook

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: