如何在Power Query中实现类似Excel COUNTIF($A$2:A2,A2)的行内计数?
Got it, let's figure out how to replicate that Excel COUNTIF($A$2:A2,A2) running count behavior in Power Query. I’ve got two solid methods for you, depending on your dataset size and preference:
Method 1: Group Rows + Add Index (Best for Large Datasets)
This method is way more efficient for big datasets, since it leverages grouping instead of slow row-by-row calculations:
- Start with your source table (let’s assume it’s named
Source). Select theNamecolumn, then go to the Transform tab and click Group By. - In the Group By dialog box, configure these settings:
- Group by: Name
- New column name:
Rows(or any name you like) - Operation: All Rows
- Click OK, and you’ll have a table where each row contains a Name and a nested table of all its occurrences.
- Next, add a custom column with this formula:
This adds an index starting at 1 to each nested group of rows.Table.AddIndexColumn([Rows], "Occurrence", 1, 1) - Finally, click the expand icon on the custom column you just created, choose to expand all columns, and clean up by removing the original
Rowscolumn. Rearrange columns if needed, and you’ll get your desired running count!
Method 2: Custom Column with Row-by-Row Calculation (Exact Excel Logic Match)
If you want a direct 1:1 match to how Excel’s COUNTIF works (great for small datasets), use this approach:
- Add a custom column to your source table with this formula:
Let’s break this down:List.Count(List.Select(List.Range(Source[Name], 0, Table.PositionOf(Source, [Name]) + 1), (x) => x = [Name]))Table.PositionOf(Source, [Name])gets the current row’s position in the tableList.Range(Source[Name], 0, ...)grabs all Name values from the start of the column up to and including the current rowList.Selectfilters that list to only match the current row’s NameList.Countcounts those matches, just like Excel’sCOUNTIF($A$2:A2,A2)
Either method will give you the exact output you showed:
Name | Occurrence
A | 1
A | 2
B | 1
A | 3
B | 2
内容的提问来源于stack exchange,提问作者Tamir
相关产品推荐
相关产品推荐

