代码之家  ›  专栏  ›  技术社区  ›  fl00r

对数组进行分组和计数

  •  0
  • fl00r  · 技术社区  · 7 年前

    arrayReduce 不适用于任意的lambda。有没有办法计算数组中元素的出现次数?就像

    select groupArray(age) from customers;
    :) [21, 40, 20, 20, 20, 30]
    select arrayReduce('groupUniqArray', groupArray(age)) from customers;
    :) [21, 40, 20, 30]
    select arrayReduce('???', groupArray(age)) from customers;
    :) [(21, 1), (40, 1), (20, 3), (30, 1)]
    

    输出格式没有那么重要。我不想在这里使用groupby/count,因为我想用一个查询聚合多个字段。

    select 
      arrayReduce('???', groupArray(age)),
      arrayReduce('???', groupArray(job)),
      arrayReduce('???', groupArray(country))
    from customers;
    

    0 回复  |  直到 7 年前
        1
  •  1
  •   vladimir    7 年前

    只需进行几次数组操作:

    SELECT
        groupArray(age) AS ages,
        arrayReduce('groupUniqArray', ages) AS uniqAges,
        arraySort(x -> x.1, arrayMap(x -> (x, countEqual(ages, x)), uniqAges)) AS resultAges,
    
        groupArray(job) AS jobs,
        arrayReduce('groupUniqArray', jobs) AS uniqJobs,
        arraySort(x -> x.1, arrayMap(x -> (x, countEqual(jobs, x)), uniqJobs)) AS resultJobs,
    
        groupArray(country) AS countries,
        arrayReduce('groupUniqArray', countries) AS uniqCountries,
        arraySort(x -> x.1, arrayMap(x -> (x, countEqual(countries, x)), uniqCountries)) AS resultCountries
    FROM test.test4
    FORMAT Vertical