I'm using SQL server and I have a table that looks like this (Table1). I want to look ahead to the next greatest AccountId value in the table by running a select statement.
Table1
| CompanyId | AccountId | CustomerId |
|---|---|---|
| 1 | 14 | 2 |
| 1 | 14 | 5 |
| 1 | 17 | 3 |
| 1 | 18 | 1 |
| 1 | 18 | 2 |
| 2 | 7 | 3 |
| 2 | 7 | 4 |
| 2 | 25 | 1 |
I've tried using lead() but that's not doing what I want. It's only looking ahead to the next 'AccountId', not the next greatest. I only want to look ahead for the same 'CompanyId' and every time the 'AccountId' changes.
Select lead(AccountId, 1) over (partition by CompanyId order by CompanyId, CustomerId) as NextAccountId
From Table1
This is my desired outcome
| CompanyId | AccountId | CustomerId | NextAccountId |
|---|---|---|---|
| 1 | 14 | 2 | 17 |
| 1 | 14 | 5 | 17 |
| 1 | 17 | 3 | 18 |
| 1 | 18 | 1 | NULL |
| 1 | 18 | 2 | NULL |
| 2 | 7 | 3 | 25 |
| 2 | 7 | 4 | 25 |
| 2 | 25 | 1 | NULL |