I have a grouped table of customers and years. I would like to add a column to identify how many consecutive years the member has been a customer.
ID | Year |
---|---|
A | 2019 |
A | 2020 |
A | 2021 |
A | 2022 |
B | 2019 |
B | 2021 |
B | 2022 |
The added formula should calculate the number of consecutive years as a customer, resetting when a year is skipped.
ID | Year | Yrs_Cust |
---|---|---|
A | 2019 | 0 |
A | 2020 | 1 |
A | 2021 | 2 |
A | 2022 | 3 |
B | 2019 | 0 |
B | 2021 | 0 |
B | 2022 | 1 |
Another alternative.
Add a single column with the following code:
= Table.AddColumn(#"Changed Type", "Custom", each [
a = Table.SelectRows(#"Changed Type", (x)=> [ID]= x[ID]),
b = List.Select( a[Year], (x)=> x <= [Year] ),
c = List.Reverse(b),
d = List.Accumulate(c, [now = [Year], run = 0],(state, current)=> [now = state[now]-1, run = if current = state[now] then state[run] + 1 else state[run] ])[run]-1
][d])