Kusto/KQL字符串列按1分钟分箱聚合及前向填充需求
Kusto查询解决方案:1分钟分箱填充+Quality分类计数
核心思路
利用make-series生成基础时间分箱聚合,结合fill forward实现空值前向填充,再通过右外连接确保覆盖完整时间范围,解决Summarize无法生成空分箱的问题。
完整查询示例
假设源数据表为SourceTable,包含Timestamp(时间列)、StringColumn(需填充的字符串列)、Quality(分类统计列):
// 模拟源数据(实际使用时替换为你的表名) let SourceTable = datatable(Timestamp:datetime, StringColumn:string, Quality:string) [ datetime(2024-01-01 00:00:00), "Value1", "Good", datetime(2024-01-01 00:02:15), "Value2", "Bad", datetime(2024-01-01 00:03:30), "Value3", "Good", datetime(2024-01-01 00:05:00), "Value4", "Unknown" ]; // 生成覆盖源数据时间范围的完整1分钟分箱序列 let fullTimeRange = range Timestamp from min(SourceTable.Timestamp) to max(SourceTable.Timestamp) step 1min; // 基于源数据生成带聚合结果的分箱 let aggregatedData = SourceTable | make-series // 每个分箱取任意非空的StringColumn值(用于后续填充) _stringVal = take_any(StringColumn) on Timestamp step 1min, // 统计各Quality类型的数量 GoodCount = countif(Quality == "Good") on Timestamp step 1min, BadCount = countif(Quality == "Bad") on Timestamp step 1min, UnknownCount = countif(Quality == "Unknown") on Timestamp step 1min // 将数组展开为行 | mv-expand Timestamp to typeof(datetime), _stringVal to typeof(string), GoodCount to typeof(long), BadCount to typeof(long), UnknownCount to typeof(long); // 合并完整时间分箱并完成前向填充 let finalResult = aggregatedData // 右外连接确保所有1分钟分箱都被保留 | join kind=rightouter fullTimeRange on Timestamp | order by Timestamp asc // 前向填充字符串列和计数列的空值 | fill forward _stringVal, GoodCount, BadCount, UnknownCount // 整理输出列名 | project Timestamp, StringColumn = _stringVal, GoodCount, BadCount, UnknownCount; finalResult
关键步骤说明
- 生成完整时间范围:用
range运算符创建覆盖源数据首尾时间的1分钟粒度时间序列,确保没有遗漏的分箱。 - make-series聚合:
take_any(StringColumn):获取每个分箱内的任意非空字符串值,为后续填充提供基础。countif(Quality == "..."):分别统计每个分箱内各类Quality的数量。
- mv-expand展开:将
make-series生成的数组类型结果展开为行格式,方便后续处理。 - 右外连接+前向填充:通过
join kind=rightouter关联完整时间序列,再用fill forward将空分箱的字符串值和计数填充为上一个分箱的有效值。
适配你的场景
- 如果Quality的分类更多,只需新增对应的
countif(Quality == "分类名")行。 - 若需要扩展时间范围(比如覆盖全天而非仅源数据的时间区间),可将
range的起始和结束时间改为固定值,如startofday(datetime(2024-01-01))到endofday(datetime(2024-01-01))。
内容的提问来源于stack exchange,提问作者Anders Fredborg
相关产品推荐
相关产品推荐

