KDB: select the first n rows from each group

How can I extract the first n lines from each group? For example: for table bb:([]sym:(4#`a),(5#`b);val: til 9)

  sym   val
  -------------
  a     0
  a     1
  a     2
  a     3
  b     4
  b     5
  b     6
  b     7
  b     8

How can I select the first 2 lines of each group using sym?

thanks

+4
source share
2 answers

You can use fby:

q)select from bb where ({x in 2#x};i) fby sym
sym val
-------
a   0
a   1
b   4
b   5
+4
source

You can try the following:

q)select from t where i in raze exec 2#i by sym from t
sym val
-------
a   0
a   1
b   4
b   5
+2
source

Source: https://habr.com/ru/post/1612238/


All Articles