select column from a table based on a variable name in q kdb

心不动则不痛 提交于 2020-01-17 01:37:46

问题


I have a table with columns sym and px

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

Now, if I assign sym column to variable ab

ab:`sym

Then, running below query is giving rank error

select ab from t / 'rank
select `ab from t / 'rank

I have a requirement where I need to save the column name to a variable based on a condition and then run select query on the column which is assigned to variable.

Followed 'Q for Mortals' and 'Reference card' but no help.


回答1:


There are a couple of ways you could achieve this. If the table is not keyed then simply use # with that column name (note that the left hand argument must be a list):

enlist[ab]#t
sym
----
GOOG
IBM
APPL

An alternative is to use functional form, for example:

q)?[t;();0b;enlist[ab]!enlist ab]
sym
----
GOOG
IBM
APPL

You can get the form of this query from the parse tree, for example:

q)parse"select ab from t"
?
`t
()
0b
(,`ab)!,`ab

The following is a more generic function for the functional select:

q){?[x;();0b;{x!x}(),y]}[t;ab]
sym
----
GOOG
IBM
APPL


来源:https://stackoverflow.com/questions/56110469/select-column-from-a-table-based-on-a-variable-name-in-q-kdb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!