For each customer's invoice, show the previous and next invoice dates. This helps analyze purchase frequency patterns.
Write a SQL query using LEAD() and LAG() to show previous and next invoice dates for each customer.
| Column | Type |
|---|---|
| InvoiceId | INTEGER (Primary Key) |
| CustomerId | INTEGER (Foreign Key → Customer.CustomerId) |
| InvoiceDate | TIMESTAMP |
| BillingAddress | TEXT |
| BillingCity | TEXT |
| BillingState | TEXT |
| BillingCountry | TEXT |
| BillingPostalCode | TEXT |
| Total | NUMERIC(10,2) |
| Column | Type |
|---|---|
| CustomerId | INTEGER (Primary Key) |
| FirstName | TEXT |
| LastName | TEXT |
| Company | TEXT |
| Address | TEXT |
| City | TEXT |
| State | TEXT |
| Country | TEXT |
| PostalCode | TEXT |
| Phone | TEXT |
| Fax | TEXT |
| TEXT | |
| SupportRepId | INTEGER (Foreign Key → Employee.EmployeeId) |
LAG(column) OVER (PARTITION BY ... ORDER BY ...) - Previous row valueLEAD(column) OVER (PARTITION BY ... ORDER BY ...) - Next row valueReady to take your skills to the next level? Enroll in our comprehensive Data Analyst Career Track to master SQL, Python, Excel, and Power BI.
Run your code to see the result here.