如何在KQL中基于id与InstanceId匹配合并行?
解决方案
方法1:自连接(精准匹配关联)
直接筛选出目标name的行,再和包含成本数据的行按id == InstanceId做关联,就能合并所需字段:
YourTable | where name == "vmTest-ip" | join kind=inner ( YourTable | where isnotempty(InstanceId) and isnotempty(MonthlyPreTaxCost) ) on $left.id == $right.InstanceId | project id, name, InstanceId, MonthlyPreTaxCost
如果需要保留vmTest-ip记录(即使没有匹配到成本),可以把kind=inner换成kind=leftouter,此时无匹配的MonthlyPreTaxCost会显示为空。
方法2:聚合合并同ID行
如果同一ID对应多条分散字段的行,可通过聚合函数把非空字段整合:
YourTable | where name == "vmTest-ip" or (isnotempty(InstanceId) and isnotempty(MonthlyPreTaxCost)) | summarize name = take_any(name), MonthlyPreTaxCost = take_any(MonthlyPreTaxCost) by id = coalesce(id, InstanceId) | project id, name, InstanceId = id, MonthlyPreTaxCost
这里用coalesce(id, InstanceId)把两个ID字段统一为关联键,take_any会提取每个键对应的非空值,最后映射回InstanceId字段。
关键注意事项
- 确保
id和InstanceId数据类型一致,若类型不同(如一个是字符串、一个是数值),需转换后再匹配,示例:| join kind=inner (...) on $left.id == tostring($right.InstanceId) - 若同一ID对应多条成本记录,可根据需求替换聚合函数,比如用
sum(MonthlyPreTaxCost)求和、max(MonthlyPreTaxCost)取最大值。
内容的提问来源于stack exchange,提问作者Stijn Berendse
相关产品推荐
相关产品推荐

