2021-02-02 12:00:41 +00:00
|
|
|
|
---
|
2022-08-26 19:07:59 +00:00
|
|
|
|
slug: /zh/sql-reference/aggregate-functions/reference/topk
|
2022-04-10 23:08:18 +00:00
|
|
|
|
sidebar_position: 108
|
2021-02-02 12:00:41 +00:00
|
|
|
|
---
|
|
|
|
|
|
|
|
|
|
# topK {#topk}
|
|
|
|
|
|
2021-03-01 15:16:07 +00:00
|
|
|
|
返回指定列中近似最常见值的数组。 生成的数组按值的近似频率降序排序(而不是值本身)。
|
2021-02-02 12:00:41 +00:00
|
|
|
|
|
2022-09-28 12:21:58 +00:00
|
|
|
|
实现了[过滤节省空间](https://doi.org/10.1016/j.ins.2010.08.024)算法, 使用基于reduce-and-combine的算法,借鉴[并行节省空间](https://doi.org/10.1016/j.ins.2015.09.003)。
|
2021-03-01 15:16:07 +00:00
|
|
|
|
|
|
|
|
|
**语法**
|
2021-02-02 12:00:41 +00:00
|
|
|
|
|
|
|
|
|
``` sql
|
2021-03-07 14:18:15 +00:00
|
|
|
|
topK(N)(x)
|
2021-02-02 12:00:41 +00:00
|
|
|
|
```
|
2021-03-01 15:16:07 +00:00
|
|
|
|
此函数不提供保证的结果。 在某些情况下,可能会发生错误,并且可能会返回不是最高频的值。
|
2021-02-02 12:00:41 +00:00
|
|
|
|
|
2021-03-01 15:16:07 +00:00
|
|
|
|
我们建议使用 `N < 10` 值,`N` 值越大,性能越低。最大值 `N = 65536`。
|
2021-02-02 12:00:41 +00:00
|
|
|
|
|
2021-03-01 15:16:07 +00:00
|
|
|
|
**参数**
|
2021-02-02 12:00:41 +00:00
|
|
|
|
|
2021-03-07 14:18:15 +00:00
|
|
|
|
- `N` — 要返回的元素数。
|
2021-02-02 12:00:41 +00:00
|
|
|
|
|
2021-03-01 15:16:07 +00:00
|
|
|
|
如果省略该参数,则使用默认值10。
|
2021-02-02 12:00:41 +00:00
|
|
|
|
|
2021-03-01 15:16:07 +00:00
|
|
|
|
**参数**
|
2021-02-02 12:00:41 +00:00
|
|
|
|
|
2021-03-07 14:18:15 +00:00
|
|
|
|
- `x` – (要计算频次的)值。
|
2021-02-02 12:00:41 +00:00
|
|
|
|
|
2021-03-01 15:16:07 +00:00
|
|
|
|
**示例**
|
2021-02-02 12:00:41 +00:00
|
|
|
|
|
2021-03-01 15:16:07 +00:00
|
|
|
|
就拿 [OnTime](../../../getting-started/example-datasets/ontime.md) 数据集来说,选择`AirlineID` 列中出现最频繁的三个。
|
2021-02-02 12:00:41 +00:00
|
|
|
|
|
|
|
|
|
``` sql
|
|
|
|
|
SELECT topK(3)(AirlineID) AS res
|
|
|
|
|
FROM ontime
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
``` text
|
|
|
|
|
┌─res─────────────────┐
|
|
|
|
|
│ [19393,19790,19805] │
|
|
|
|
|
└─────────────────────┘
|
|
|
|
|
```
|