如何使用KQL实现类似SQL的Partition By分组求和与占比计算?
KQL实现分组内用户请求占比计算
给定原始数据:
| Group | UserId | count_ |
|---|---|---|
| 1 | 2 | 2 |
| 1 | 1 | 3 |
| 2 | 3 | 3 |
| 2 | 4 | 7 |
要实现每个分组内用户请求数占分组总请求数的比例,输出如下格式:
| Group | UserId | percent |
|---|---|---|
| 1 | 2 | 0.4 |
| 1 | 1 | 0.6 |
| 2 | 3 | 0.3 |
| 2 | 4 | 0.7 |
对应的KQL查询语句如下:
your_table_name | extend group_total = sum(count_) over (partition by Group) | extend percent = round(toreal(count_) / group_total, 1) | project Group, UserId, percent
说明:
sum(count_) over (partition by Group):和SQL窗口函数逻辑一致,计算每个Group分组的总请求数,生成临时列group_total。toreal(count_) / group_total:将整数类型的count_转为数值类型后除以分组总数得到占比;round(...,1)用于保留1位小数,匹配预期输出格式。project:筛选出需要的列,对应预期输出的结构。
如果不需要强制保留1位小数,直接计算即可:
your_table_name | extend percent = toreal(count_) / sum(count_) over (partition by Group) | project Group, UserId, percent
内容的提问来源于stack exchange,提问作者JeyJ
相关产品推荐
相关产品推荐

