Kdb+聚合函数动态by子句失效问题求助
Kdb+ 动态分组聚合函数修正
普通Select版本问题与修正
错误原因
普通SQL语法中,by groupCol会将groupCol解析为字面列名,而非传入的变量值,导致无法按指定列分组,最终返回一行汇总结果。
修正后的代码
agg:{[data; groupCol; labels] eval parse "select req:count i where priced=`Y, vol:(sum qty where priced=`Y)%1e6, reqDealt:count i where status in (`DEALT), volDealt:(sum qty where status in (`DEALT))%1e6, reqPcnt:(count i where status in (`DEALT))% (count i where priced=`Y), volPcnt:(sum qty where status in (`DEALT))% (sum qty where priced=`Y) by ", string groupCol, " from data where label in ", string labels }
通过parse将字符串转为q表达式,再用eval执行,实现动态替换分组列和过滤标签。
函数式Select版本问题与修正
错误原因
- Where条件中错误使用符号
labels而非变量labels,导致过滤逻辑未生效; - By子句错误使用符号
groupCol作为键值对,而非传入的变量groupCol的值,导致分组逻辑失效; - 存在大小写不一致的
DEAlT,可能导致匹配失败。
修正后的代码
agg:{[data; groupCol; labels] ?[ data; enlist (in; `label; labels); // 使用变量labels而非符号`labels (enlist groupCol)!enlist groupCol; // 使用传入的groupCol变量作为分组列 (`req`vol`reqDealt`volDealt`reqPcnt`volPcnt)! ( (count; `i; (where; (=; `priced; enlist `Y))); (%; (sum; `qty; (where; (=; `priced; enlist `Y))); 1e6); (count; `i; (where; (in; `status; enlist `DEALT))); (%; (sum; `qty; (where; (in; `status; enlist `DEALT))); 1e6); (%; (count; `i; (where; (in; `status; enlist `DEALT))); (count; `i; (where; (=; `priced; enlist `Y)))); (%; (sum; `qty; (where; (in; `status; enlist `DEALT))); (sum; `qty; (where; (=; `priced; enlist `Y)))) ) ] }
函数式查询更适合动态参数场景,直接通过变量传递分组列和过滤条件,避免字符串拼接的繁琐。
内容的提问来源于stack exchange,提问作者vicefreak04
相关产品推荐
相关产品推荐

