如何将数组传递给更新查询 kdb

how to pass an array into update query kdb

你好,我有以下代码,我想找到传递任意大小数组的最佳方法,而不必逐行显式地执行:

这两个数组是coeffs和tickers。谢谢

t:update Value:Value*coeffs[0] from (select from t)where Code in `$tickers[0];
t:update Value:Value*coeffs[1] from (select from t)where Code in `$tickers[1];
t:update Value:Value*coeffs[2] from (select from t)where Code in `$tickers[2];
t:update Value:Value*coeffs[3] from (select from t)where Code in `$tickers[3];
t:update Value:Value*coeffs[4] from (select from t)where Code in `$tickers[4];

假设两个数组的长度相同,那么您可以尝试创建一个 tickerscoeffs:

的字典
dict:(`$tickers)!coeffs

然后可以在 update 语句中使用:

update Value:Value*1^dict[Code] from t

1^ 在这里至关重要,因为使用不存在的键索引到 dict 将 return 为空。此表示法允许您使用 1 fill 空值,从而确保 Value 保持不变。

另一种方法是使用 lj.

q)t:([] n:til 10; Value:1+til 10; Code:10#`a`b`c`d`e)
q)tickers:enlist each "abcdf"

使用 tickerscoeffs 创建 keyed table kt :

q)kt:([Code:`$tickers] coeffs:2 4 6 8 10 )
q)kt
Code| coeffs
----| ------
a   | 2
b   | 4
c   | 6
d   | 8
f   | 10

现在加入 tkt

q)t:t lj kt
q)t
n Value Code coeffs
-------------------
0 1     a    2
1 2     b    4
2 3     c    6
3 4     d    8
4 5     e
5 6     a    2
6 7     b    4
7 8     c    6
8 9     d    8
9 10    e

更新 table t 我们有 non-null coeff

q)update Value:Value*coeffs from t where not null coeffs
n Value Code coeffs
-------------------
0 2     a    2
1 8     b    4
2 18    c    6
3 32    d    8
4 5     e
5 12    a    2
6 28    b    4
7 48    c    6
8 72    d    8
9 10    e
  • 使用 lj,您最终会多出一个列 coeffs,您可能想要删除它。
  • 这在您有多个映射(tickers->coeffstickers->delta 等)时特别有用,您只需要创建一个包含所有映射的 table。