"indirection" for column names in Q queries

How do I use the name of a column stored in a variable in a Q query?

Here is the specific question:

I have a table:

       .ta.t:( col1:1 2 3;col2:aa`b)

I can do an easy aggregate query:

       select sum col1 by col2 from .ta.t 

Now say instead I have:

       colname:`col2

I would like to be able to do the same query but specifying the “by” column using my colname variable.

Following do not work:

       select sum col1 by colname from .ta.t

       select sum col1 by `colname from .ta.t

       select sum col1 by (value colname) from .ta.t

Thanks in advance,

Just a note - I know I can construct the whole thing as a string and evaluate it.
So this works:

eval parse “select sum col1 by “,string[colname],” from .ta.t”

I was wondering if there is something else. Why? I have a fairly complex multi-line query that aggregates data in a table.

I would like to be able to aggregate by different columns and provide one function that I can call with the name of the column to aggregate by.

The eval/parse solution would work, but then my function and complex query becomes one large string to concatenate - workable, but not the most elegant solution.

http://code.kx.com/wiki/JB:QforMortals2/queries_q_sql#Functional_select

Cheers,

  Attila

Thanks - perfect.

look at aaron’s wrapper functions to help you get started (and to keep the code understandable):

http://www.q-ist.com/2012/10/functional-query-functions.html

and

http://www.q-ist.com/2013/03/my-kdb-user-meeting-presentation.html

Thanks much Simon - will take a look at Aaron’s code. I am not working on that particular problem currenlty - when I get back to it, I will try out the above suggestions and post back if there is anything of interest to others.