如何在Kusto中基于App分组计算各Code的请求占比?
按App分组计算请求数占比的Kusto实现
你可以通过窗口函数或者分组关联的方式实现按App分组计算请求占比,以下是两种可行方案:
方案一:使用窗口函数(推荐,更简洁高效)
datatable (Code:string, App:string, Requests:long) [ "200", "tra", 63, "200", "api", 1036, "302", "web", 12, "200", "web", 219, "500", "web", 2, "404", "api", 18 ] | extend AppTotalRequests = sum(Requests) over (partition by App) | extend Percentage = round(100.0 * Requests / AppTotalRequests, 2) | project Code, App, Requests, AppTotalRequests, Percentage
核心逻辑是用sum(Requests) over (partition by App)为每一行计算对应App的总请求数,再用当前行的请求数除以该分组总数,得到占比并保留两位小数。比如api分组的总请求数为1054,200状态的请求占比就是1036/1054*100≈98.29%,符合预期。
方案二:使用分组关联
如果更熟悉join语法,也可以先按App分组计算总数,再关联原表:
datatable (Code:string, App:string, Requests:long) [ "200", "tra", 63, "200", "api", 1036, "302", "web", 12, "200", "web", 219, "500", "web", 2, "404", "api", 18 ] | as T | join kind=inner ( T | summarize AppTotalRequests = sum(Requests) by App ) on App | extend Percentage = round(100.0 * Requests / AppTotalRequests, 2) | project Code, App, Requests, AppTotalRequests, Percentage
内容的提问来源于stack exchange,提问作者LukeB
相关产品推荐
相关产品推荐

