如何用KQL基于TimeGenerated和Success字段计算对应总秒数
Kusto脚本实现时间差计算与分组汇总
需求1:获取每行对应的秒数
通过partition by按Success分组,每组内序列化时间字段后计算当前行与下一行的时间差,得到每条记录对应的持续秒数:
// 替换your_table_name为实际表名 your_table_name | partition by Success ( serialize TimeGenerated | extend next_record_time = next(TimeGenerated) | extend duration_seconds = datetime_diff('second', next_record_time, TimeGenerated) // 处理每组最后一条无后续记录的情况,秒数设为0 | extend duration_seconds = iif(isnull(duration_seconds), 0, duration_seconds) )
需求2:按Success分组汇总总秒数
基于需求1的结果,通过summarize按Success维度求和得到总秒数:
// 替换your_table_name为实际表名 your_table_name | partition by Success ( serialize TimeGenerated | extend next_record_time = next(TimeGenerated) | extend duration_seconds = datetime_diff('second', next_record_time, TimeGenerated) | extend duration_seconds = iif(isnull(duration_seconds), 0, duration_seconds) ) | summarize total_seconds = sum(duration_seconds) by Success
说明
partition by Success确保仅在同Success状态的记录组内计算时间差,避免跨状态干扰serialize用于固定组内记录按TimeGenerated的排序顺序,保证next()函数取到正确的后续记录datetime_diff直接计算两个时间的秒级差值,最后处理每组末尾无后续记录的边界情况
内容的提问来源于stack exchange,提问作者user2281447
相关产品推荐
相关产品推荐

