有没有一种简单的方法在表格的一组列中找到第二大或第二小的数字?
使用select min
/max (a, b, c, d) by i from t
可以轻松地找到最大或最小值。
然而,我似乎找不到一种简单的方法来从该组中找到第二(或第三)大或小的数字。
谢谢
如果你只想要第二大/小的值,你可以使用以下方法:
q) a: 4 3 5 1 6 8
q) max a except max a / second maximum
q) min a except min a / second minimum
如果您希望有一个通用函数适用于任何第n个最大/小值,这里有一种方法:
对于第N个最大值
f:a (idesc a)[n-1]
q) a (idesc a)[2-1] // second maximum
对于第N小值
f: a (iasc a)[n-1]
q) a (iasc a)[2-1] // second minimum
rank
来完成这个任务:q)a:10?100
q)a
65 93 15 82 76 14 75 78 44 79
q)f:{x where y=rank x}
q)f[a;1] / second smallest
,15
q)f[a;2] / third smallest
,44
我认为q语言中没有反向rank
函数,因此你可以这样做:
q)f2:{x where y=iasc idesc x}
q)f2[a;1] / second biggest
,82
q)f2[a;2] / third biggest
,79
iasc
/idesc
doesn't account for ties unfortunately and OP doesn't specifically preclude ties. Take for example third largest:6~a (idesc a:4 2 5 1 6 6 8 8)[3-1]
, correct is5~
- Daniel Krizian