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

PowerQuery新增AVG_TIME_DIFF列:计算同A值行平均时间差

PowerQuery 新增AVG_TIME_DIFF列实现方案

原始数据表格

IDABCCOUNTTimestamp
1a1c102017-05-10 09:55:28
a3bc22017-05-10 10:12:54
2a2c322017-05-10 10:19:47
a2bc42017-05-10 10:20:24
a2bc52017-05-10 10:21:50
3a3c612017-05-10 10:31:02
a3cc72017-05-10 10:31:02

注:COUNT列仅对ID非空的行生效,统计同A值且B等于“b”的行数。

AVG_TIME_DIFF列规则

  • 仅对ID非空的行进行处理
  • 若COUNT值为0,返回“0”
  • 若COUNT值不为0,取同A值且B等于“b”的所有行的Timestamp,加上当前行的Timestamp,按时间排序后计算平均时间差(单位:秒,小数部分可按需取舍)
  • 其余行结果为空

预期结果

IDABCCOUNTTimestampAVG_TIME_DIFF
1a1c102017-05-10 09:55:280
a3bc22017-05-10 10:12:54
2a2c322017-05-10 10:19:4762
a2bc42017-05-10 10:20:24
a2bc52017-05-10 10:21:50
3a3c612017-05-10 10:31:021088
a3cc72017-05-10 10:31:02

PowerQuery M代码实现

加载原始数据进入PowerQuery编辑器后,添加自定义列AVG_TIME_DIFF,输入以下代码:

if [ID] <> null then
    if [COUNT] = 0 then
        "0"
    else
        let
            currentA = [A],
            currentTS = [Timestamp],
            filteredTS = Table.SelectRows(Source, each [A] = currentA and [B] = "b")[Timestamp],
            allTS = List.Sort(List.Combine({filteredTS, {currentTS}})),
            timeDiffs = List.Generate(
                () => [index=1, diff=Duration.TotalSeconds(allTS{index} - allTS{index-1})],
                each [index] < List.Count(allTS),
                each [index=[index]+1, diff=Duration.TotalSeconds(allTS{index} - allTS{index-1})],
                each [diff]
            ),
            avgDiff = Number.Round(List.Average(timeDiffs), 0)
        in
            Text.From(avgDiff)
else
    null

代码说明

  • 先判断ID是否非空,仅对非空行执行计算逻辑
  • COUNT为0时直接返回"0"
  • 筛选同A且B="b"的所有Timestamp,合并当前行Timestamp后排序
  • 计算相邻时间的秒级差值,取平均值并取整后转为文本格式
  • ID为空的行返回空值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:21:00