azure KQL -获取多列值的总和

pxq42qpu  于 2023-10-22  发布在  其他
关注(0)|答案(2)|浏览(92)

我从一个查询中得到以下数据:

Service 201 202 401  // 402 etc
A       100 50  20   
C       25  0   0

柱子是动态的。有时只有201,有时200,201,202,204等
我想得到以下结果:

Service 201 202 503  2xxCount  5xxCount
A       100 50  20   150       20        
C       25  0   0    25        0

就像我说的,柱子是动态的。我想计算所有名称以2开头的列的总和,作为2xxCount,5作为5xxCount。

cngwdvgl

cngwdvgl1#

您可以通过两个步骤来实现这一点-首先动态生成查询,然后执行它:
1.生成查询:

let T = datatable (Service:string, ['201']:long, ['202']:long, ['401']:long)
[
    "A", 100, 50, 20, 
    "C", 25, 0, 0
];
T | getschema 
| where ColumnName != "Service"
| extend Column = bin(tolong(ColumnName), 100)
| summarize make_list(strcat("['", ColumnName, "']")) by Column
| project strcat("['", Column/100, "xxCount'] = ", strcat_array(list_, " + "))
| summarize ExtendedColumns = strcat_array(make_list(Column1), ", ")

| ExtendedColumns|
| --|
| “2xxCount”] =“201”] +“202”],“4xxCount”] =“401”]|
1.运行它:

let T = datatable (Service:string, ['201']:long, ['202']:long, ['401']:long)
[
    "A", 100, 50, 20, 
    "C", 25, 0, 0
];
T
| extend ['2xxCount'] = ['201'] + ['202'], ['4xxCount'] = ['401']

| 服务| 201 | 202 | 401 |2xxCount| 4xxCount|
| --|--|--|--|--|--|
| 一| 100 | 50 | 20 | 150 | 20 |
| C| 25 | 0 | 0 | 25 | 0 |

xzv2uavs

xzv2uavs2#

您应该能够通过组合使用narrowpivot来实现这一点:

let T = datatable (Service:string, ['201']:long, ['202']:long, ['401']:long)
[
    "A", 100, 50, 20, 
    "C", 25, 0, 0
];
let categorizedData=T
| evaluate narrow()
| parse Column with "['" Code "']"
| extend Column = coalesce(Code, Column)   // strip the [' '] from the column names
| extend CodeCategory = strcat(toint(Code)/100, 'xx');
let sumByCategory=categorizedData
| where isnotempty(Code)
| summarize Value=tostring(sum(toint(Value))) by Column=CodeCategory, Row;
categorizedData
| union sumByCategory
| project-away Code, CodeCategory
| evaluate pivot(Column, take_any(Value))
| project-away Row

测试结果:
| 201 | 202 |2xx| 401 |4xx|服务|
| --|--|--|--|--|--|
| 25 | 0 | 25 | 0 | 0 |C|
| 100 | 50 | 150 | 20 | 20 |一|
唯一有点烦人的是,你不能控制pivot返回的列顺序,但是如果最大列数是固定的,你可以硬编码一个重排序,如果它对你很重要的话。

相关问题