在Power Query中为动态添加列填充日期差相关计算值
Power Query动态列计算填充方案
之前通过本站解决过问题,在此致谢。目前有新需求:已构建的表格中前3列来自数据源,第4列及以后的列标题是根据列表rngMakeSpan动态添加的,当前已用List.Accumulate创建了这些空列,现在需要为这些动态列填充计算值。
计算规则:initial value加上0.05乘以「start」日期与对应列标题的日期天数差。
现有代码:
let Source = Excel.CurrentWorkbook(){[Name="tblTestData"]}[Content], #"Changed Type" = Table.TransformColumnTypes(Source,{{"characteristic", type text}, {"initial value", type number}, {"start", type date}}), Custom1 = List.Accumulate(rngMakeSpan, #"Changed Type", (state, current) => Table.AddColumn(state, current, each null)) in Custom1
修改后的实现代码
不用额外再调用一次List.Accumulate,直接在创建列的步骤里替换空值逻辑为计算逻辑即可:
let Source = Excel.CurrentWorkbook(){[Name="tblTestData"]}[Content], #"Changed Type" = Table.TransformColumnTypes(Source,{{"characteristic", type text}, {"initial value", type number}, {"start", type date}}), Custom1 = List.Accumulate(rngMakeSpan, #"Changed Type", (state, current) => Table.AddColumn(state, current, each [initial value] + (0.05 * Duration.Days(Date.From(current) - [start])) ) ) in Custom1
关键说明
- 把原代码中创建空列的
each null替换为计算表达式,直接在添加列时完成赋值 Date.From(current)用于确保列标题的日期格式正确转换(如果rngMakeSpan中的元素本身就是日期类型,可移除该转换)Duration.Days()计算两个日期之间的天数差,得到数值后参与后续运算
内容的提问来源于stack exchange,提问作者koen
相关产品推荐
相关产品推荐

