cjm2671
cjm2671

Reputation: 19466

How do I parameterise the column list in KDB?

I have a number of repetitive queries:

select lR, e10, e25, vr from z

Is there a way I can do something like:

features: `lR`e10`e25`vr

select features from z

Upvotes: 0

Views: 114

Answers (3)

SeanHehir
SeanHehir

Reputation: 1593

If you use # for this then be aware it will fail on a keyed table.
One possible way of modifying it to work on any table would be something like:

f:{[t;c] if[not .Q.qt[t]; '"Input is not a table"]; c,:(); $[99h = type[t];c#/:t;c#t]}

So make sure your table is, in fact, a table, make sure columns are a list, and then perform the required # operation.

q)t
a| b c d
-| ------
a| 4 7 10
b| 5 8 11
c| 6 9 12
q)f[t;`b]
a| b
-| -
a| 4
b| 5
c| 6
q)f[0!t;`b]
b
-
4
5
6
q)f[flip 0!t;`b]
'Input is not a table
  [0]  f[flip 0!t;`b]
       ^

Upvotes: 1

terrylynch
terrylynch

Reputation: 13572

Another approach is to use a functional form (which you can build using parse):

q)0N!parse"select lR, e10, e25, vr from z";
(?;`z;();0b;`lR`e10`e25`vr!`lR`e10`e25`vr)

q)features:`lR`e10`e25`vr
q)?[z;();0b;features!features]

Upvotes: 1

Matthew Madill
Matthew Madill

Reputation: 880

You could use # like so:

`lR`e10`e25`vr#z

NB: The left argument here must be a list so to select a single column use the following:

enlist[`vr]#z

Example:

q)t:([]a:`a`b`c;b:til 3;c:0b);
q)`a`b#t
a b
---
a 0
b 1
c 2

Upvotes: 1

Related Questions