查询选择 N 条记录
query for selecting N records
我有一个 table tab
,它有 cols date,sym,value
并且是从最早的日期到最近的日期排序的。
我正在尝试 select 每个 sym
的过去 N
记录,但不确定对此的查询。我知道我可以 select 基于 date
在一个范围内,但我需要它基于 sym
而不管 value
是否出现在连续的日期。
您可以使用 fby
和虚拟行号列 i
:
https://code.kx.com/q/ref/fby/
q){ select from tab where ({y in x#y}[x];i) fby sym }[-2]
date sym time src price size
------------------------------------------------------------
2014.04.21 AAPL 2014.04.21D16:29:03.253000000 N 24.98 3561
2014.04.21 AAPL 2014.04.21D16:29:03.558000000 N 24.98 2733
2014.04.21 CSCO 2014.04.21D16:28:56.265000000 O 35.6 8390
2014.04.21 CSCO 2014.04.21D16:29:44.572000000 L 35.61 2286
2014.04.21 DELL 2014.04.21D16:29:35.374000000 L 29.57 1444
2014.04.21 DELL 2014.04.21D16:29:39.979000000 N 29.56 216
2014.04.21 GOOG 2014.04.21D16:29:50.569000000 N 41.87 722
2014.04.21 GOOG 2014.04.21D16:29:58.633000000 O 41.9 437
编辑:更快的方法是对每个符号使用带有第 5 个参数 n(记录数)的函数式 exec。
raze{
//[table;where;by;cols;rows]
?[tab;enlist (in;`sym;enlist x);0b;();y]
}[;-2]'[distinct tab[`sym]]
如果您希望返回 table 中的所有列,Matt 使用 fby
和功能性 select 的建议是最好的。如果您只需要返回 date
、sym
和 price
列,您可以使用
q)ungroup select -2#date,-2#price by sym from trade
sym date price
----------------------
APPL 2021.03.13 111.77
APPL 2021.03.13 111.85
CAT 2021.03.13 246
CAT 2021.03.13 246.27
GOOG 2021.03.13 206.24
GOOG 2021.03.13 206.21
NYSE 2021.03.13 60.67
NYSE 2021.03.13 60.97
请注意,当 select 处理大量列时,这会变得乏味。在这些情况下,最好坚持 Matt 的建议。
我有一个 table tab
,它有 cols date,sym,value
并且是从最早的日期到最近的日期排序的。
我正在尝试 select 每个 sym
的过去 N
记录,但不确定对此的查询。我知道我可以 select 基于 date
在一个范围内,但我需要它基于 sym
而不管 value
是否出现在连续的日期。
您可以使用 fby
和虚拟行号列 i
:
https://code.kx.com/q/ref/fby/
q){ select from tab where ({y in x#y}[x];i) fby sym }[-2]
date sym time src price size
------------------------------------------------------------
2014.04.21 AAPL 2014.04.21D16:29:03.253000000 N 24.98 3561
2014.04.21 AAPL 2014.04.21D16:29:03.558000000 N 24.98 2733
2014.04.21 CSCO 2014.04.21D16:28:56.265000000 O 35.6 8390
2014.04.21 CSCO 2014.04.21D16:29:44.572000000 L 35.61 2286
2014.04.21 DELL 2014.04.21D16:29:35.374000000 L 29.57 1444
2014.04.21 DELL 2014.04.21D16:29:39.979000000 N 29.56 216
2014.04.21 GOOG 2014.04.21D16:29:50.569000000 N 41.87 722
2014.04.21 GOOG 2014.04.21D16:29:58.633000000 O 41.9 437
编辑:更快的方法是对每个符号使用带有第 5 个参数 n(记录数)的函数式 exec。
raze{
//[table;where;by;cols;rows]
?[tab;enlist (in;`sym;enlist x);0b;();y]
}[;-2]'[distinct tab[`sym]]
Matt 使用 fby
和功能性 select 的建议是最好的。如果您只需要返回 date
、sym
和 price
列,您可以使用
q)ungroup select -2#date,-2#price by sym from trade
sym date price
----------------------
APPL 2021.03.13 111.77
APPL 2021.03.13 111.85
CAT 2021.03.13 246
CAT 2021.03.13 246.27
GOOG 2021.03.13 206.24
GOOG 2021.03.13 206.21
NYSE 2021.03.13 60.67
NYSE 2021.03.13 60.97
请注意,当 select 处理大量列时,这会变得乏味。在这些情况下,最好坚持 Matt 的建议。