KDB+中trade表工作日/周末数据筛选报错问题排查
KDB+ 工作日/周末交易数据查询报错排查与解决
报错原因
原查询语句在where子句中错误地将日期筛选逻辑直接嵌套在within运算符后:
t1hr_weekdays: select avg tv by 1 xbar ts.hh from trade where date within daterange where 1<daterange mod 7, sym=`BTCUSDT
KDB+的within运算符要求传入明确的日期列表,上述写法相当于在within后直接追加筛选条件,属于语法错误,最终触发length类型不匹配报错。
正确实现方法
需先预先生成工作日日期列表和周末日期列表,再将其传入within完成筛选:
1. 生成目标日期范围的工作日/周末列表
// 定义日期边界 firstdate:2023.01.01 lastdate:2023.01.10 // 生成完整日期范围 daterange:firstdate + til (lastdate - firstdate) + 1 // 筛选工作日(周一至周五:date mod 7 结果为2-6) daterange_weekdays: daterange where 1<daterange mod 7 // 筛选周末(周日至周六:date mod 7 结果为0-1) daterange_weekends: daterange where (daterange mod 7) in 0 1
2. 查询工作日交易数据
t1hr_weekdays: select avg tv by 1 xbar ts.hh from trade where date within daterange_weekdays, sym=`BTCUSDT
3. 查询周末交易数据
t1hr_weekends: select avg tv by 1 xbar ts.hh from trade where date within daterange_weekends, sym=`BTCUSDT
补充优化方案
若无需预先生成全量日期范围,可直接在where子句中对date字段做模运算筛选,省去中间列表生成步骤:
// 直接筛选工作日 t1hr_weekdays: select avg tv by 1 xbar ts.hh from trade where 1<date mod 7, date within (firstdate;lastdate), sym=`BTCUSDT // 直接筛选周末 t1hr_weekends: select avg tv by 1 xbar ts.hh from trade where (date mod 7) in 0 1, date within (firstdate;lastdate), sym=`BTCUSDT
内容的提问来源于stack exchange,提问作者Qbie_to_Qmortal
相关产品推荐
相关产品推荐

