kdb/q技术实现:统计表中Name-Item列对买卖次数并筛选双交易组合
筛选kdb/q中同时存在Buy和Sell操作的Name-Item组合
原始数据定义
sample_data: ([] Name: `Ann`Ann`Ann`Bob`Bob`Bob`Bob; Item: `Apple`Apple`Bread`Apple`Salt`Salt`Salt; Action: `Buy`Sell`Sell`Buy`Buy`Buy`Sell; Price: 5.00 6.00 9.00 5.00 1.00 1.00 2.00)
需求说明
需要找出所有同时发生过至少一次Buy和Sell操作的Name-Item组合。
方法一:分两步实现(按计划生成中间表)
1. 生成统计中间表
按Name和Item分组,统计每组内Buy和Sell的操作次数:
stats_table: select Buys:count[i] where Action=`Buy, Sells:count[i] where Action=`Sell by Name, Item from sample_data
生成的中间表如下:
| Name | Item | Buys | Sells |
|---|---|---|---|
| Ann | Apple | 1 | 1 |
| Ann | Bread | 0 | 1 |
| Bob | Apple | 1 | 0 |
| Bob | Salt | 2 | 1 |
2. 筛选符合条件的组合
从中间表中筛选Buys≥1且Sells≥1的记录,仅保留Name和Item列:
result: select Name, Item from stats_table where Buys >=1, Sells >=1
最终结果:
| Name | Item |
|---|---|
| Ann | Apple |
| Bob | Salt |
方法二:一步到位实现
无需生成中间表,直接分组后检查每组是否同时包含Buy和Sell操作:
// 先按Name-Item分组去重Action,再筛选同时包含Buy和Sell的组 result: select Name, Item from (select distinct Action by Name, Item from sample_data) where all (`Buy`Sell) in Action
该方法逻辑更简洁,执行效率也更高,最终结果与方法一一致。
内容的提问来源于stack exchange,提问作者mmv456
相关产品推荐
相关产品推荐

