2020-06-18 08:24:31 +00:00
|
|
|
---
|
2022-08-28 14:53:34 +00:00
|
|
|
slug: /en/sql-reference/aggregate-functions/reference/avgweighted
|
2022-04-09 13:29:05 +00:00
|
|
|
sidebar_position: 107
|
2020-06-18 08:24:31 +00:00
|
|
|
---
|
|
|
|
|
2022-06-02 10:55:18 +00:00
|
|
|
# avgWeighted
|
2020-06-18 08:24:31 +00:00
|
|
|
|
|
|
|
Calculates the [weighted arithmetic mean](https://en.wikipedia.org/wiki/Weighted_arithmetic_mean).
|
|
|
|
|
|
|
|
**Syntax**
|
|
|
|
|
|
|
|
``` sql
|
|
|
|
avgWeighted(x, weight)
|
|
|
|
```
|
|
|
|
|
2021-02-15 21:33:53 +00:00
|
|
|
**Arguments**
|
2020-06-18 08:24:31 +00:00
|
|
|
|
2020-10-19 15:23:35 +00:00
|
|
|
- `x` — Values.
|
|
|
|
- `weight` — Weights of the values.
|
2020-06-18 08:24:31 +00:00
|
|
|
|
2020-10-19 15:23:35 +00:00
|
|
|
`x` and `weight` must both be
|
|
|
|
[Integer](../../../sql-reference/data-types/int-uint.md),
|
2021-07-29 15:20:55 +00:00
|
|
|
[floating-point](../../../sql-reference/data-types/float.md), or
|
2020-10-19 15:23:35 +00:00
|
|
|
[Decimal](../../../sql-reference/data-types/decimal.md),
|
|
|
|
but may have different types.
|
2020-06-18 08:24:31 +00:00
|
|
|
|
|
|
|
**Returned value**
|
|
|
|
|
2020-10-30 16:17:57 +00:00
|
|
|
- `NaN` if all the weights are equal to 0 or the supplied weights parameter is empty.
|
2020-10-19 15:23:35 +00:00
|
|
|
- Weighted mean otherwise.
|
2020-06-18 08:24:31 +00:00
|
|
|
|
2020-10-25 20:33:01 +00:00
|
|
|
**Return type** is always [Float64](../../../sql-reference/data-types/float.md).
|
2020-06-18 08:24:31 +00:00
|
|
|
|
|
|
|
**Example**
|
|
|
|
|
|
|
|
Query:
|
|
|
|
|
|
|
|
``` sql
|
|
|
|
SELECT avgWeighted(x, w)
|
|
|
|
FROM values('x Int8, w Int8', (4, 1), (1, 0), (10, 2))
|
|
|
|
```
|
|
|
|
|
|
|
|
Result:
|
|
|
|
|
|
|
|
``` text
|
|
|
|
┌─avgWeighted(x, weight)─┐
|
|
|
|
│ 8 │
|
|
|
|
└────────────────────────┘
|
|
|
|
```
|
2020-10-15 10:36:00 +00:00
|
|
|
|
|
|
|
**Example**
|
|
|
|
|
|
|
|
Query:
|
|
|
|
|
|
|
|
``` sql
|
|
|
|
SELECT avgWeighted(x, w)
|
|
|
|
FROM values('x Int8, w Float64', (4, 1), (1, 0), (10, 2))
|
|
|
|
```
|
|
|
|
|
|
|
|
Result:
|
|
|
|
|
|
|
|
``` text
|
|
|
|
┌─avgWeighted(x, weight)─┐
|
|
|
|
│ 8 │
|
|
|
|
└────────────────────────┘
|
|
|
|
```
|
2020-10-30 16:17:57 +00:00
|
|
|
|
|
|
|
**Example**
|
|
|
|
|
|
|
|
Query:
|
|
|
|
|
|
|
|
``` sql
|
|
|
|
SELECT avgWeighted(x, w)
|
|
|
|
FROM values('x Int8, w Int8', (0, 0), (1, 0), (10, 0))
|
|
|
|
```
|
|
|
|
|
|
|
|
Result:
|
|
|
|
|
|
|
|
``` text
|
|
|
|
┌─avgWeighted(x, weight)─┐
|
|
|
|
│ nan │
|
|
|
|
└────────────────────────┘
|
|
|
|
```
|
|
|
|
|
|
|
|
**Example**
|
|
|
|
|
|
|
|
Query:
|
|
|
|
|
|
|
|
``` sql
|
|
|
|
CREATE table test (t UInt8) ENGINE = Memory;
|
|
|
|
SELECT avgWeighted(t) FROM test
|
|
|
|
```
|
|
|
|
|
|
|
|
Result:
|
|
|
|
|
|
|
|
``` text
|
|
|
|
┌─avgWeighted(x, weight)─┐
|
|
|
|
│ nan │
|
|
|
|
└────────────────────────┘
|
|
|
|
```
|