英文:
How to calculate the k-th largest value in a sequence in DolphinDB?
问题
如何计算序列中的第k个最大值?是否需要对序列进行排序,然后按索引获取值?是否有更简单和更有效的方法可用?
英文:
I would like to know how to calculate the k-th largest value in a sequence. Is it required to sort the sequence and then retrieve the value by index? Are there any simpler and more efficient methods available?
答案1
得分: 1
你可以使用函数searchK,它专门用于查找第k个最小元素。要计算第k个最大元素,您需要计算序列的总长度,然后从中减去k。
请注意,以下语句不能用于SQL查询,因为分布式查询尚不支持嵌套聚合函数:
select searchK(val, count(val)-k) from t
这将导致错误消息:“无法将聚合函数用作另一个聚合函数的参数”。
您可以首先计算总记录数“rows”,然后将rows-k用作searchK
的参数:
rows = sum(getTabletsMeta("/testDB/%", `pt, true).rowNum);
select searchK(volume, rows-k) from t
英文:
You can use the function searchK, which is designed to find the k-th smallest element. To calculate the k-th largest element, you need to calculate the total length of the sequence and subtract k from it.
Note that the following statement cannot be used in SQL queries, because nested aggregate functions are not yet supported in distributed queries:
select searchK(val, count(val)-k) from t
This will result in an error message: Can't use an aggregate function as the argument of another aggregate function
.
You can first calculate the total record count ”rows“ and then use rows-k as the parameter in searchK
:
rows = sum(getTabletsMeta("/testDB/%", `pt, true).rowNum);
select searchK(volume, rows-k) from t
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论