You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求PowerQuery函数:获取重复数据的附加列信息

PowerQuery 重复数据标记函数

以下是实现需求的PowerQuery自定义函数,可针对指定列集合标记重复项的首次出现ID及组内计数器,非重复项返回null:

let
    AddDuplicationInfo = (inputTable as table, keyColumns as list, idColumn as text) as table =>
    let
        // 按指定键列分组,计算每组最小ID和总条数
        Grouped = Table.Group(inputTable, keyColumns, {
            {"MinRowId", each List.Min(Table.Column(_, idColumn)), type nullable number},
            {"TotalRows", each Table.RowCount(_), type number},
            {"GroupData", each _}
        }),
        // 展开分组数据,保留原表所有列
        Expanded = Table.ExpandTableColumn(Grouped, "GroupData", Table.ColumnNames(inputTable)),
        // 生成组内计数器(仅重复组生效,从1开始计数)
        AddCounter = Table.AddColumn(Expanded, "nDupl", each 
            if [TotalRows] > 1 then 
                Table.RowCount(Table.SelectRows(Expanded, (r) => 
                    List.AllTrue(List.Transform(keyColumns, (col) => r[col] = [col])) and Record.Field(r, idColumn) <= Record.Field(_, idColumn)
                )) 
            else null, type nullable number
        ),
        // 重命名列并调整非重复项的MinRowId值
        RenameCols = Table.RenameColumns(AddCounter, {{"MinRowId", "DuplInfo.MinRowId"}}),
        AdjustMinRowId = Table.AddColumn(RenameCols, "DuplInfo.MinRowId_Adjusted", each 
            if [TotalRows] > 1 then [DuplInfo.MinRowId] else null, type nullable number
        ),
        // 清理临时列,得到最终结果
        CleanedTable = Table.RemoveColumns(Table.RenameColumns(AdjustMinRowId, {{"DuplInfo.MinRowId_Adjusted", "DuplInfo.MinRowId"}}), {"TotalRows"})
    in
        CleanedTable
in
    AddDuplicationInfo

参数说明

  • inputTable:待处理的源数据表
  • keyColumns:用于判定重复的列集合(示例:{"Date", "Product", "Color"})
  • idColumn:作为唯一标识的ID列名称(需为可排序类型,如数值、日期)

使用示例

假设你的源数据表名为SalesRecords,ID列名为RowId,调用方式如下:

AddDuplicationInfo(SalesRecords, {"Date", "Product", "Color"}, "RowId")

核心逻辑

  1. 分组统计:按指定列分组,计算每组的最小ID和总记录数,区分重复组与非重复组
  2. 展开数据:还原分组后的明细数据,保留原表所有字段
  3. 生成计数器:仅对重复组(总记录数>1),统计当前行在组内的出现顺序
  4. 调整非重复项:对无重复的组,将DuplInfo.MinRowId和DuplInfo.nDupl设为null
  5. 清理输出:移除临时计算列,保留最终需要的标记字段

内容的提问来源于stack exchange,提问作者Denis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 05:31:34