在选择查询中,根据q kdb中的if -else if条件设置列值

时间:2019-05-20 13:46:51

标签: kdb

我们有一个表t:

t:([] sym:`GOOG`IBM`APPL; px:10 20 30; size:1000 2000 3000)

现在,我们要根据函数中提供的条件选择在输出中分配一列。

{[m]select sym, px, size, eb:?[`ab=m;`cd;`ef] from t where size>1000}[`ab] / This works fine providing proper value to eb in output(if/else)

但是我的要求是基于(if / else if)将eb的值设置如下,尝试了?,$,但是没有用

{[m]select sym, px, size, eb:?[`ab=m;`cd;`yz=m;`ef] from t where size>1000}[`ab] / It fails with type error 

我的要求(Sudo代码):

if (m==ab) { return cd};
else if (m==yz) {return ef};

2 个答案:

答案 0 :(得分:5)

使用向量条件?时,您需要嵌套条件。在此示例中,两个条件都不匹配将返回null。

q){[m]select sym, px, size, eb:?[`ab=m;`cd;?[`yz=m;`ef;`]] from t where size>1000}[`ab]
sym  px size eb
---------------
IBM  20 2000 cd
APPL 30 3000 cd

如果您有很多离散条件,这可能会变得很笨拙,则可以选择使用字典。

q)dict:`ab`yz!`cd`ef
q){[m]select sym, px, size, eb:dict[m] from t where size>1000}[`ab]
sym  px size eb
---------------
IBM  20 2000 cd
APPL 30 3000 cd

答案 1 :(得分:2)

您还可以使用find [?]运算符来定义用于构建该列的函数:

q)f:{`cd`ef` `ab`yz?x}
q)f[`ab]
`cd
q)f[`yz]
`ef
q)f[`jk] // no match
`
q)select sym, px, size, eb:f[`ab] from t where size>1000
sym  px size eb
---------------
IBM  20 2000 cd
APPL 30 3000 cd