跳转到内容

使用 HyperLogLog 算法估算数据集中不同值的数量。

HyperLogLog 算法以极少的内存和时间提供唯一元素数量的近似值。处理可接受估算结果的大型数据集时,可以考虑使用此函数。它以牺牲部分精度为代价,提供了一种快速高效的返回去重计数的方法。

若要获得精确的结果,请使用 COUNT_DISTINCT。更多说明请参阅示例。

func.approx_count_distinct(<expr>)
func.approx_count_distinct(table.user_id).alias('approx_distinct_user_count')
| approx_distinct_user_count |
|----------------------------|
| 4 |
APPROX_COUNT_DISTINCT(<expr>)

整数。

创建表并插入示例数据

CREATE TABLE user_events (
id INT,
user_id INT,
event_name VARCHAR
);
INSERT INTO user_events (id, user_id, event_name)
VALUES (1, 1, 'Login'),
(2, 2, 'Login'),
(3, 3, 'Login'),
(4, 1, 'Logout'),
(5, 2, 'Logout'),
(6, 4, 'Login'),
(7, 1, 'Login');

查询演示:估算不同用户 ID 的数量

SELECT APPROX_COUNT_DISTINCT(user_id) AS approx_distinct_user_count
FROM user_events;

结果

| approx_distinct_user_count |
|----------------------------|
| 4 |