Power Query M Code: Keep First Duplicate and Replace Null with Zero
Here is the Power Query (M) code that keeps the first instance of duplicates, blanks the rest,
and replaces null with zero:
```
let
Source = #"PreviousStep",
// Add row index to preserve original order
AddIndex = [Link](Source, "RowIndex", 1, 1),
// Group by ID + Amount and add occurrence number
GroupAddIndex =
[Link](AddIndex, {"ID","Amount"}, {
{"Data", (t)=> [Link](t, "Occ", 1, 1), type table}
}),
// Expand back
Expand = [Link](
GroupAddIndex, "Data",
{"ID","Amount","RowIndex","Occ"}
),
// Keep first duplicate, blank others
BlankDuplicates =
[Link](
Expand,
{
{"ID", each if [Occ] = 1 then _ else null},
{"Amount", each if [Occ] = 1 then _ else null}
}
),
// Replace nulls with 0
ReplaceNulls =
[Link](BlankDuplicates, null, 0, [Link], {"ID","Amount"}),
// Remove helper column
Clean = [Link](ReplaceNulls, {"Occ"})
in
Clean
```