问题
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