Kusto查询如何按条件取指定列首值 首名含J取首条score其余保留原值
场景说明
需要在Kusto中按条件实现数据查询,具体示例源表如下:
| first_name | second_name | type | score | date. |
|---|---|---|---|---|
| John | Adam | student | 67. | 2021-8-4 |
| John | Adam | student | 89. | 2021-8-3 |
| John | Adam | student | 75. | 2021-8-2 |
| James | Smith | student | 80. | 2021-8-2 |
| Sam | Miles | student | 69. | 2021-8-3 |
查询需求
编写查询语句实现如下逻辑:若first_name字段包含字符"J",则取该first_name对应分组下score列的第一条值,否则保留score原有值,最终输出first_name、second_name、score三个字段。
预期结果
| first_name | second_name | score |
|---|---|---|
| John | Adam | 67. |
| James | Smith | 80. |
| Sam | Miles | 69. |
解决方案
以下KQL语句可直接实现需求,默认按照示例中的「日期倒序」作为「第一条」的判断规则,你可以根据实际业务调整排序逻辑:
// 实际使用时将下方datatable部分替换为你自己的表名即可 datatable(first_name:string, second_name:string, type:string, score:decimal, date:datetime) [ "John", "Adam", "student", decimal(67.), datetime(2021-08-04), "John", "Adam", "student", decimal(89.), datetime(2021-08-03), "John", "Adam", "student", decimal(75.), datetime(2021-08-02), "James", "Smith", "student", decimal(80.), datetime(2021-08-02), "Sam", "Miles", "student", decimal(69.), datetime(2021-08-03) ] // 核心查询逻辑 | partition by first_name ( order by date desc // 可修改此处的排序字段调整「第一条」的判断规则 | take iff(first_name has "J", 1, toscalar(your_table_name | count)) // 含J的分组仅取排序后第一条,不含J的保留全部分组数据 ) | project first_name, second_name, score
逻辑说明:
- 使用
partition按first_name分组处理,实现不同分组的差异化逻辑 has运算符判断姓名是否包含J,性能优于contains,需要区分大小写可替换为has_cs- 最终输出字段完全匹配需求,和预期结果一致
内容的提问来源于stack exchange,提问作者MaxDev
相关产品推荐
相关产品推荐

