【问题标题】:Workaround to count percents of unique values in ClickHouse计算 ClickHouse 中唯一值百分比的解决方法
【发布时间】:2019-11-25 08:47:22
【问题描述】:

我在计算唯一值的百分比时遇到了麻烦。用精确值(总计、总和等)计算百分比是没有问题的。但是uniq 函数的结果总是不同的,这是可以理解的。主要问题是百分比不加起来。例如,total unique 是 5000,但总和可能是 4999 或 5001。例如:

WITH (
    SELECT uniq(t.id)
    FROM test.table t
) AS total

SELECT t.name as gender,
       t.age as age,
       uniq(t.id) as uniques,
       COALESCE((( uniques / total ) * 100), 0) as uniquesPercent
FROM test.table t
GROUP BY gender, age

那么,有什么方法可以解决这个问题。由于性能问题,我无法使用 uniqExact。提前谢谢你。

【问题讨论】:

    标签: clickhouse


    【解决方案1】:

    假设同一用户不能有多个性别或年龄(换句话说,同一用户不能出现在多个组中),那么 total 可以计算为每个组的唯一计数的总和:

    SELECT result.1 gender, result.2 age, result.3 uniquesPercent
    FROM (
      SELECT 
        groupArray((gender, age, uniques)) groups,
        arraySum(x -> x.3, groups) total,
        arrayJoin(arrayMap(x -> (x.1, x.2, x.3 / total), groups)) result
      FROM (
        SELECT
            t.name AS gender,
            t.age AS age,
            uniq(t.id) AS uniques
        FROM test.table AS t
        GROUP BY
            gender,
            age
        )
      )
    

    【讨论】:

    • 它为所有组提供相同的百分比,这是错误的。但我会努力改进这种方法,谢谢
    猜你喜欢
    • 2021-03-16
    • 1970-01-01
    • 2015-10-11
    • 2020-06-19
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    相关资源
    最近更新 更多