Forum Discussion
List.Generate to calculate column based on the previous row value of the Same Column
Hello DSR,
Thank you for posting your query in the Microsoft Fabric Community Forum regarding the calculation of a column based on the previous row's value using List.Generate in Power Query. I have successfully replicated your scenario in Power BI Desktop and would like to share the steps I followed, along with the expected output and a PBIX file for your reference.
Steps I Followed:
- Created Sample Data: I manually entered the following data into Power BI Desktop:
|
Case.CC.EEName |
PeriodNo |
Yr |
NoEE.inPrvPrd |
Yr Move Out |
NoEE |
Index.inGrp |
|
A |
0 |
Yr00 |
0 |
2 |
0 |
0 |
|
A |
1 |
Yr01 |
0 |
2 |
1 |
1 |
|
A |
2 |
Yr02 |
1 |
2 |
2 |
2 |
|
A |
3 |
Yr03 |
1 |
2 |
1 |
3 |
|
A |
4 |
Yr04 |
1 |
2 |
0 |
4 |
|
A |
5 |
Yr05 |
0 |
2 |
1 |
5 |
|
A |
6 |
Yr06 |
1 |
2 |
0 |
6 |
|
A |
7 |
Yr07 |
0 |
2 |
0 |
7 |
|
A |
8 |
Yr08 |
0 |
2 |
0 |
8 |
|
A |
9 |
Yr09 |
0 |
2 |
0 |
9 |
|
A |
10 |
Yr10 |
0 |
2 |
0 |
10 |
- Opened Power Query Editor: I imported the data into Power Query by selecting Transform Data.
- Added Custom Calculated Column: I implemented the following M code to create the new calculated column, CalculatedNoEE:
Code:
let
index = [Index.inGrp],
noEE = [NoEE],
yrMoveOut = [Yr Move Out],
previousValues = List.Generate(
() => [Value = 0, Index = 0],
each [Index] <= index,
each [
Value = if [Index] = 0 then 0
else if noEE = 0 or noEE = null then null
else if [Value] = yrMoveOut then noEE
else [Value] + 1,
Index = [Index] + 1
],
each [Value]
),
result = List.Last(previousValues)
in
result
- Reviewed and Applied Changes: After adding the custom column, I verified the calculations.
- I have attached a screenshot of the output table showing the newly calculated column:
- Additionally, I have attached the PBIX file for your convenience.
If this helps, then please Accept it as a solution and dropping a "Kudos" so other members can find it more easily.
Hope this works for you!
Thank you.
Hello V-ssriganesh, Thank you for your work. rom your table result your codes do not get the correct result. the Answer shall be:
| Answershallbe |
| 1 |
| 2 |
| 1 |
| 1 |
I have updated the request. please review if the conditions