如何在KQL中透视数据表?附示例数据与预期结果
KQL查询实现透视表转换(去除test_name下划线)
原始数据表定义
let input = datatable (name:string, test_name:string, value:int) [ "VM01", "test_1", 0, "VM01", "test_2", 1, "VM01", "test_3", 1, "VM01", "test_4", 2, "VM01", "test_5", 2, "VM02", "test_1", 2, "VM02", "test_2", 1, "VM02", "test_3", 1, "VM02", "test_4", 1, "VM02", "test_5", 2, "VM03", "test_1", 1, "VM03", "test_2", 1, "VM03", "test_3", 1, "VM03", "test_4", 0, "VM03", "test_5", 2, "VM04", "test_1", 1, "VM04", "test_2", 1, "VM04", "test_3", 1, "VM04", "test_4", 1, "VM04", "test_5", 2, "VM05", "test_1", 1, "VM05", "test_2", 1, "VM05", "test_3", 2, "VM05", "test_4", 2, "VM05", "test_5", 1, ];
转换目标格式
| test_name | VM01 | VM02 | VM03 | VM04 | VM05 |
|---|---|---|---|---|---|
| test1 | 0 | 2 | 1 | 1 | 1 |
| test2 | 1 | 1 | 1 | 1 | 1 |
| test3 | 1 | 1 | 1 | 1 | 2 |
| test4 | 2 | 1 | 0 | 1 | 2 |
| test5 | 2 | 2 | 2 | 2 | 1 |
实现KQL查询
input | extend test_name = replace_string(test_name, "_", "") | pivot(name, any(value)) | project test_name, VM01, VM02, VM03, VM04, VM05
代码说明
- 去除下划线:用
replace_string函数将test_name中的下划线替换为空,得到符合要求的测试名称 - 透视转换:
pivot函数把name字段的不同值(VM01~VM05)转为列,any(value)提取每个分组对应的value值(因每组name+test_name唯一,any可精准获取对应值) - 列序调整:
project函数指定输出列顺序,和目标格式保持一致
内容的提问来源于stack exchange,提问作者Vitamin C
相关产品推荐
相关产品推荐

