如何编写KQL查询统计各TenantID的占比?
KQL查询:统计TenantID的记录占比
可以通过分组统计、计算总记录数后求比值的方式实现,以下是两种高效的写法:
方法一:利用分组总和计算(推荐,仅扫描一次表)
// 假设你的数据表名为YourTable YourTable | summarize TenantCount = count() by TenantID // 按TenantID分组统计每组记录数 | let total = sum(TenantCount); // 计算所有分组的记录总和(即总记录数) | extend Proportion = todouble(TenantCount) / total // 计算占比,转double避免整数除法 | project TenantID, Proportion // 输出目标列
方法二:通过标量查询获取总记录数
YourTable | summarize TenantCount = count() by TenantID | extend TotalCount = toscalar(YourTable | count) // 单独查询总记录数并加入每行 | extend Proportion = todouble(TenantCount) / TotalCount | project TenantID, Proportion
测试验证
如果需要直接验证逻辑,可以用模拟数据测试:
datatable(TenantID:string) [ "A", "A", "B", "B", "C" ] | summarize TenantCount = count() by TenantID | let total = sum(TenantCount); | extend Proportion = todouble(TenantCount) / total | project TenantID, Proportion
执行后会得到预期结果:
| TenantID | Proportion |
|---|---|
| A | 0.4 |
| B | 0.4 |
| C | 0.2 |
内容的提问来源于stack exchange,提问作者kevin
相关产品推荐
相关产品推荐

