You could do this a few ways. The preferred would be to write the select statement functionally. There is a function called parse which can help us construct the functional form of a query. Basically, it takes a string as a parameter (our select statement) and returns the parse tree of this. We then use this parse tree to construct the functional version. This is easier to explain with an example;
q)parse"select s,p from sp"
?
`sp
()
0b
`s`p!`s`p
q)
//we can use this output to build the functional version of the query. This would be;
q)?[sp;();0b;`s`p!`s`p]
//so if we run the above, it will return the same as running q)select s,p from sp
// the difference which is useful to us, is that we can specify the columns by passing in symbols. So we need to figure out how to dynamically generate a list of columns as symbols using column indexes. To do this, we get a list of columns and index into them;
q)cols sp
`s`p`qty
q)(cols sp)0 2
`s`qty
//for simplicity we can assign this to a variable called 'kols', we can then incorporate this variable into our functional query
q)kols:(cols sp)0 2
q)?[sp;();0b;kols!kols]
//thats it. We can make a function out of this code which will take two parameters. The table and the indexes of the columns we want. This function would be;
q)f:{[tab;idx] kols:(cols tab)idx; ?[tab;();0b;kols!kols]}
//here is is in action;
q)f[sp;0 2]
s qty
------
s1 300
s1 200
s1 400
s1 200
s4 100
s1 100
s2 300
s2 400
s3 200
s4 200
s4 300
s1 400
q)f[sp;0 1]
s p
-----
s1 p1
s1 p2
s1 p3
s1 p4
s4 p5
s1 p6
s2 p1
s2 p2
s3 p2
s4 p2
s4 p4
s1 p5
q)
//Let me know if this helps!
Thanks,
Michael
--
--
From: Xinyu Gai Sent: Friday, March 4, 2016 05:42 To: Kdb+ Personal Developers Reply To: personal...@googlegroups.com |
Subject: Re: [personal kdb+] Re: select columns from a table |