# topKWeighted (/docs/reference/sql/aggregate-functions/topkweighted)



This page describes the RawTree engine binary used to generate this reference. It does not define Query API support. Descriptions retain upstream ClickHouse terminology. See [SQL interface scope](/docs/reference/clickhouse-compatibility#service-interfaces).

Returns an array of the approximately most frequent values in the specified column.
The resulting array is sorted in descending order of approximate frequency of values (not by the values themselves).
Additionally, the weight of the value is taken into account.

**See Also**

* [topK](/reference/functions/aggregate-functions/topK)
* [approx\_top\_k](/reference/functions/aggregate-functions/approxtopk)
* [approx\_top\_sum](/reference/functions/aggregate-functions/approxtopsum)

**Syntax**

```sql
topKWeighted(N)(column, weight)
topKWeighted(N, load_factor)(column, weight)
topKWeighted(N, load_factor, 'counts')(column, weight)
```

**Parameters**

* `N` — The number of elements to return. Default value: 10. [`UInt64`](/reference/data-types/int-uint)
* `load_factor` — Optional. Defines, how many cells reserved for values. If `uniq(column) > N * load_factor`, result of topK function will be approximate. Default value: 3. [`UInt64`](/reference/data-types/int-uint)
* `counts` — Optional. Defines whether the result should contain an approximate count and error value. [`Bool`](/reference/data-types/boolean)

**Arguments**

* `column` — The name of the column for which to find the most frequent values. - `weight` — The weight. Every value is accounted `weight` times for frequency calculation. [`UInt64`](/reference/data-types/int-uint)

**Returned value**

Returns an array of the values with maximum approximate sum of weights. [`Array`](/reference/data-types/array)

**Examples**

**Usage example**

```sql title=Query
SELECT topKWeighted(2)(k, w) FROM
VALUES('k Char, w UInt64', ('y', 1), ('y', 1), ('x', 5), ('y', 1), ('z', 10));
```

```text title=Response
┌─topKWeighted(2)(k, w)──┐
│ ['z','x']              │
└────────────────────────┘
```

**With counts parameter**

```sql title=Query
SELECT topKWeighted(2, 10, 'counts')(k, w)
FROM VALUES('k Char, w UInt64', ('y', 1), ('y', 1), ('x', 5), ('y', 1), ('z', 10));
```

```text title=Response
┌─topKWeighted(2, 10, 'counts')(k, w)─┐
│ [('z',10,0),('x',5,0)]              │
└─────────────────────────────────────┘
```

*Introduced in version 1.1.0.*
