kdb

terser form to select the first row for a keyed table


Suppose I have a table

q) t:([]
    name:`c`c`c`w`w;
    id:1 1 1 2 1;
    c:2 4 5 4 3
 );

q)show t;
name id c
---------
c    1  2
c    1  4
c    1  5
w    2  4
w    1  3

and I would like to get the first row given the composite grouping of name and id.

Since I only have one column I can do

q)select first c by name,id from t
name id c
---------
c    1  2
w    2  4
w    1  3

which gives me the required result. However, suppose I have several other columns (apart from name, id, c) making it inconvenient to type

select first c, first col1, first col2, ...,first colN by name,id from t 

Is there something terser?


Solution

  • Use fby https://code.kx.com/q/ref/fby/#tables

    q)select from t where i=(first;i) fby ([] name; id)
    name id c
    ---------
    c    1  2
    w    2  4
    w    1  3
    q)