在q kdb中选择所有带后缀_test的列

时间:2019-08-19 11:52:39

标签: kdb

我有一个分区表,类似于下表:

q)t:([]date:3#2019.01.01; a:1 2 3; a_test:2 3 4; b_test:3 4 5; c: 6 7 8);

date       a a_test b_test c
----------------------------
2019.01.01 1 2      3      6
2019.01.01 2 3      4      7
2019.01.01 3 4      5      8

现在,我想获取日期列,并且所有列的名称都从表t中带有后缀“ _test”。
预期输出:

date       a_test b_test
------------------------
2019.01.01 2      3
2019.01.01 3      4
2019.01.01 4      5

在我的原始表中,有100多个名称为_test的列,因此在这种情况下,下面的方法不可行。

q)select date, a_test, b_test from t where date=2019.01.01

我尝试了如下所示的各种选项,但没有用:

q)delete all except date, *_test from select from t where date=2019.01.01

2 个答案:

答案 0 :(得分:2)

如果您选择的列是可变的,则应使用functional qSQL语句执行查询。以下内容适用于您的情况

q)query:{[tab;dt;c]?[tab;enlist (=;`date;dt);0b;(`date,c)!`date,c]}
q)query[t;2019.01.01;cols[t] where cols[t] like "*_*"]
date       a_test b_test
------------------------
2019.01.01 2      3
2019.01.01 3      4
2019.01.01 4      5

为了制作特定的函数语句,您可以解析查询,如果不确定不确定的列应该放置伪列

q)parse "select date,c1,c2 from tab where date=dt"
?
`tab
,,(=;`date;`dt)
0b
`date`c1`c2!`date`c1`c2

答案 1 :(得分:2)

如果需要添加其他过滤器,功能选择可能是最好的选择。

?[`t;();0b;{x!x}`date,exec c from meta t where c like "*_test"]

使用-5可以获得任何选择查询的功能形式!任何SQL样式语句上的运算符。 在下面的示例中,我创建了一个包含20个字段的表,每个字段以a或b开头。 然后,我使用函数形式来定义我想要的字段。

q)tab:{[x] enlist x!count[x]#0}`$"_" sv ' raze string `a`b,/:\:til 10

q){[t;s]?[t;();0b;{[x] x!x} cols[t] where cols[t] like s]}[tab;"b*"]
b_0 b_1 b_2 b_3 b_4 b_5 b_6 b_7 b_8 b_9
---------------------------------------
0   0   0   0   0   0   0   0   0   0

q){[t;s]?[t;();0b;{[x] x!x} cols[t] where cols[t] like s]}[tab;"a*"]
a_0 a_1 a_2 a_3 a_4 a_5 a_6 a_7 a_8 a_9
---------------------------------------
0   0   0   0   0   0   0   0   0   0

q)-5!" select a,b from c"
?
`c
()
0b
`a`b!`a`b

或者,如果我不需要任何过滤,则可以使用#运算符,如下所示:

{[x;s] (cols[x] where cols[x]  like s)#x}[ tab;"a*"]