如何删除sql中last关键字的冗余使用

how to remove redundant use of last keyword in qsql

我有一个 table:

q)t:([] sym:`AAPL`MSFT`AMZN`AAPL`MSFT`AMZN; px:1 2 3 11 22 33; sh:100 200 300 1000 2000 3000)

我想通过sym得到最后的px和sh,可以使用两次last函数得到:

q)select last px, last sh by sym from t
sym | px sh
----| -------
AAPL| 11 1000
AMZN| 33 3000
MSFT| 22 2000

如何只使用一次last关键字来得到上面的输出?(因为在实际情况中有时我们需要在30多个列上使用last)

我失败的尝试:

q)select last (px;sh) by sym from t
q)select {last x}@'(px;sh) by sym from t

对于这种情况,使用 by 短语而不选择列与将 last 应用于所有列相同。

select by sym from t

应该可以解决问题

q)(select last px, last sh by sym from t)~select by sym from t
1b

解决该问题的常见方法是使用 fby,它允许您在所有列中应用 firstlast(或 lambda)等函数:

t:([]c1:10?`A`B`C;c2:10?10;c3:10?"xyz";c4:.z.D-til 10)

q)select from t where i=(last;i)fby c1
c1 c2 c3 c4
-------------------
A  9  z  2019.10.01
C  7  y  2019.09.29
B  0  x  2019.09.28

q)select from t where i=({first x};i)fby c1
c1 c2 c3 c4
-------------------
B  6  x  2019.10.07
C  6  x  2019.10.06
A  4  y  2019.10.02

要在关于每列应用不同函数的评论中回答您的问题,您必须使用函数 select 例如:

q)?[t;();{x!x}1#`c1;{x!((first;last)x in `c2`c4),'x}cols[t]except`c1]
c1| c2 c3 c4
--| ----------------
A | 9  y  2019.10.01
B | 0  x  2019.09.28
C | 7  x  2019.09.29

这对 c2 和 c4 列使用 last,然后对其他列使用 first