使用Power Query为重复InvoiceNo生成出现次数索引列的问题
为重复InvoiceNo添加出现次数索引列
问题说明
我有一个包含重复InvoiceNo值的数据集,需要添加名为“Occurrence”的索引列,统计每个InvoiceNo的出现次数,期望效果如下:
| InvoiceNo | Occurrence |
|---|---|
| 100011 | 1 |
| 100012 | 1 |
| 100013 | 1 |
| 100011 | 2 |
| 100011 | 3 |
| 100012 | 2 |
| 100014 | 1 |
尝试以下代码时出现报错:We cannot convert the value 100011 to type list,出错代码:
initialTable = Table.FromColumns(InvoiceNo, type table [Occurrence = text]), grouped = Table.Group(initialTable, "InvoiceNo", {{"toCombine", each Table.AddIndexColumn(_, "Occurrences", 1, 1), type table}}), combined = Table.Combine(grouped[toCombine]) in combined
错误原因
Table.FromColumns要求第一个参数是列表的列表,但代码直接传入单个InvoiceNo列的值,导致类型不匹配。- 代码中创建的索引列名为
Occurrences,与需求的Occurrence不一致。
修正后的代码
假设你的原始数据源表名为Source,替换为实际引用后使用以下M代码:
Source = 你的原始数据源, // 替换成实际数据源(如Excel.CurrentWorkbook(){[Name="表名"]}[Content]) // 按InvoiceNo分组,为每组添加从1开始的索引列,列名设为Occurrence Grouped = Table.Group(Source, {"InvoiceNo"}, {{"GroupedData", each Table.AddIndexColumn(_, "Occurrence", 1, 1), type table}}), // 合并所有分组后的表 Combined = Table.Combine(Grouped[GroupedData]) in Combined
关键说明
- 直接基于原始表分组,避免手动构建表时的类型错误。
- 确保索引列名与需求一致。
- 分组依据使用
{"InvoiceNo"}列表格式,符合Table.Group的参数要求。
内容的提问来源于stack exchange,提问作者user31722869
相关产品推荐
相关产品推荐

