如何在 clickhouse 中聚合数组类型
Posted
技术标签:
【中文标题】如何在 clickhouse 中聚合数组类型【英文标题】:How to aggregate array type in clickhouse 【发布时间】:2020-02-23 18:15:08 【问题描述】:这是示例表
示例表:
id | weeklyNumber |
---- -------------
1 | [2,5,9] |
------------------
2 | [1,10,4] |
预期的结果应该是weeklyNumber数组的聚合结果,即 [3,15,13] (2+1, 5+10, 9+4)
我不知道该怎么做。
-----更新---- 此外, 我们有很多行下表 示例表:
id | weeklyNumber | monthlyNumber
---- ------------- -------------
1 | [2,5,9] | [20,50,90]
--------------------------------
2 | [1,10,4] | [10,100,40]
结果应该是 [2/20 + 1/10, 5/50 + 10/100, 9/90 + 4/40]。该怎么做?
【问题讨论】:
答案已更新以涵盖问题的第二部分。 【参考方案1】:需要使用ForEach-aggregate函数组合器:
SELECT sumForEach(weeklyNumber)
FROM
(
SELECT
1 AS id,
[2, 5, 9] AS weeklyNumber
UNION ALL
SELECT
2 AS id,
[1, 10, 4] AS weeklyNumber
)
/*
┌─sumForEach(weeklyNumber)─┐
│ [3,15,13] │
└──────────────────────────┘
*/
在某些情况下可以使用这个查询:
SELECT arrayReduce('sumForEach', groupArray(weeklyNumber))
FROM
(
SELECT
1 AS id,
[2, 5, 9] AS weeklyNumber
UNION ALL
SELECT
2 AS id,
[1, 10, 4] AS weeklyNumber
)
/*
┌─arrayReduce('sumForEach', groupArray(weeklyNumber))─┐
│ [3,15,13] │
└─────────────────────────────────────────────────────┘
*/
更新
SELECT sumForEach(arrayMap((x, y) -> (x / y), weeklyNumber, monthlyNumber)) AS result
FROM
(
SELECT
1 AS id,
[2, 5, 9] AS weeklyNumber,
[20, 50, 90] AS monthlyNumber
UNION ALL
SELECT
2 AS id,
[1, 10, 4] AS weeklyNumber,
[10, 100, 40] AS monthlyNumber
)
/*
┌─result────────┐
│ [0.2,0.2,0.2] │
└───────────────┘
*/
【讨论】:
以上是关于如何在 clickhouse 中聚合数组类型的主要内容,如果未能解决你的问题,请参考以下文章
《ClickHouse企业级应用:入门进阶与实战》4 ClickHouse高级数据类型
ClickHouse 技术系列- ClickHouse 聚合函数和聚合状态