使用Kusto row_cumsum实现累计薪资超3000重置的问题
解决Kusto中累计薪资超阈值后重置累计的问题
我懂你碰到的麻烦了——用row_cumsum直接做条件重置的时候,因为没办法正确追踪上一次重置后的累计基准,所以第二次及之后的迭代逻辑就乱了。你原来的查询里,当total >=3000时用total-prev(total),其实只是取了当前行的薪资,但下一行的累计还是会基于之前未重置的大总值计算,自然没法得到想要的结果。
正确的解决方案:用scan运算符维护状态
Kusto的scan运算符专门用来处理这种需要在分组内维护状态的场景,它可以追踪当前的累计值,当超过阈值时自动重置。下面是调整后的查询:
datatable (name:string, month:int, salary:long) [ "Alice", 1, 1000, "Alice", 2, 2000, "Alice", 3, 1400, "Alice", 3, 1400, "Alice", 3, 1400, ] | order by name asc, month asc | scan with ( state current_total:long = 0; step s: current_total = iff(current_total + s.salary > 3000, s.salary, current_total + s.salary); extend is_over_threshold = current_total + s.salary > 3000; // 标记当前行是否导致累计超3000 extend cumulative_total = current_total; )
代码解释
state current_total:long = 0:定义一个状态变量,用来追踪当前的累计薪资,初始值为0。step块里的逻辑:- 先判断如果当前累计值加上该行薪资超过3000,就把
current_total重置为当前行的薪资;否则继续累加。 is_over_threshold列用来标记当前行是否导致累计总额超过3000,完全匹配你要标记该行的需求。cumulative_total列展示重置后的实时累计值。
- 先判断如果当前累计值加上该行薪资超过3000,就把
输出结果示例
| name | month | salary | is_over_threshold | cumulative_total |
|---|---|---|---|---|
| Alice | 1 | 1000 | false | 1000 |
| Alice | 2 | 2000 | true | 2000 |
| Alice | 3 | 1400 | false | 1400 |
| Alice | 3 | 1400 | false | 2800 |
| Alice | 3 | 1400 | true | 1400 |
可以看到,第二行累计到3000(1000+2000),被标记为true,同时累计值重置为2000;第五行累计2800+1400=4200超过3000,被标记为true,累计值重置为1400,完全符合你的预期。
内容的提问来源于stack exchange,提问作者Justin Mathew
相关产品推荐
相关产品推荐

