Search code examples
kdbk

Join usage scenarios


The official docs covers only the basic usage of join. But one could see how the left join lj is implemented:

q)lj
k){.Q.ft[,\:[;y];x]}
q).Q.ft
k){$[$[99h=@t:v y;98h=@. t;0];[n:#+!y;n!x 0!y];x y]}

and so one could find another use case (dict,keyed table):

/(dict,dict): add columns
d1:     `a`b  ! 1 2
d2:       `b`c!   3 4
(d1,d2)~`a`b`c! 1 3 4

/(table,table): add rows
t1:(enlist `a`b!1 2)
t2:(enlist `a`b!3 4)
(t1,t2) ~ (`a`b!1 2;`a`b!3 4)

/(keyed table,keyed table): add rows
k1:(`a`b!1 2;`a`b!3 5)!(`c`d`e!10 20 30;`c`d`e!40 50 60)
k2:(`a`b!1 2;`a`b!3 4)!(`c`d`e!15 25 35;`c`d`e!45 55 65)
(k1,k2)
/ a b| c  d  e
/ ---| --------
/ 1 2| 15 25 35
/ 3 5| 40 50 60
/ 3 4| 45 55 65

/(dict,keyed table): add cols
k2:(`a`b!1 2;`a`b!3 4)!(`c`d`e!15 25 35;`c`d`e!45 55 65)
/                  a b| c  d  e
/                  ---| --------
d1:     `a`b`c`d  !1 2  10 20
/                  1 2| 15 25 35
/                  3 4| 45 55 65
(d1,k2)~`a`b`c`d`e!1 2  15 25 35

Also there are cases with ,\: and ,' mentioned in docs. But knowing tables as dictionary lists in disguise, they are just derivatives of those listed above.

The question is - are there any other usage cases (with different argument types) of this mighty function join ,?


Solution

  • You have covered the main data structures in q, though I suppose one other way which might not be initially obvious to new users, is given functions are first class objects in q, you can use join on them, which is useful for creating parse tress.

    For example,

    t:([]col1:10?10;col2:10?10;col3:10?10)
    

    Lets say you were working with a functional query, and you wanted to select the sum of col1 and col2 individually, you could write

    ?[t;();0b;`col1`col2!((sum;`col1);(sum;`col2))]
    

    though slightly more compactly, which will become even more compact the more columns you include

    ?[t;();0b;`col1`col2!sum,/:`col1`col2]
    

    Shorter again is below, but not due to using joins

    ?[t;();0b;{x!sum,/:x}`col1`col2]