clickhouse create table 异常:在查询中发现聚合函数 minState(origin_user) 位置错误

Posted

技术标签:

【中文标题】clickhouse create table 异常:在查询中发现聚合函数 minState(origin_user) 位置错误【英文标题】:clickhouse create table Exception: Aggregate function minState(origin_user) is found in wrong place in query 【发布时间】:2021-10-17 09:25:20 【问题描述】:
CREATE TABLE user_dwd.user_tag_bitmap_local 
(
    `tag` String,
    `tag_item` String,
    `p_day` Date,
    `origin_user` UInt64,
    `users` AggregateFunction(min, UInt64) MATERIALIZED minState(origin_user)
)
ENGINE = AggregatingMergeTree()
PARTITION BY toYYYYMMDD(p_day)
ORDER BY (tag, tag_item)
SETTINGS index_granularity = 8192;

运行sql建表时,报错:

[2021-10-17 12:05:28] 代码:184,e.displayText() = DB::Exception:在查询中发现聚合函数 minState(origin_user) 位置错误:处理 minState 时(origin_user) AS users_tmp_alter9508717652815860223:默认表达式和列类型不兼容。 (版本 21.8.4.51(正式版))

如何解决错误?

【问题讨论】:

【参考方案1】:

minState 是一个聚合函数,你不能这样使用它(它用于带有 groupby 部分的查询)。 要解决它,您可以使用MATERIALIZED initializeAggregation...MATERIALIZED arrayReduce(minState...

但实际上您不需要第二列。 您正在寻找 SimpleAggregateFunction:

https://clickhouse.com/docs/en/sql-reference/data-types/simpleaggregatefunction/

CREATE TABLE user_dwd.user_tag_bitmap_local 
(
    `tag` String,
    `tag_item` String,
    `p_day` Date,
    `origin_user` SimpleAggregateFunction(min, UInt64) ---<<<-----
)
ENGINE = AggregatingMergeTree()
PARTITION BY toYYYYMMDD(p_day)
ORDER BY (tag, tag_item)
SETTINGS index_granularity = 8192;

https://clickhouse.com/docs/en/sql-reference/functions/other-functions/#initializeaggregation

CREATE TABLE user_tag_bitmap_local
(
    `tag` String,
    `tag_item` String,
    `p_day` Date,
    `origin_user` UInt64,
    `users` AggregateFunction(min, UInt64) MATERIALIZED initializeAggregation('minState', origin_user)
)
ENGINE = AggregatingMergeTree
PARTITION BY toYYYYMMDD(p_day)
ORDER BY (tag, tag_item)
SETTINGS index_granularity = 8192

https://clickhouse.com/docs/en/sql-reference/functions/array-functions/#arrayreduce

CREATE TABLE user_tag_bitmap_local
(
    `tag` String,
    `tag_item` String,
    `p_day` Date,
    `origin_user` UInt64,
    `users` AggregateFunction(min, UInt64) MATERIALIZED arrayReduce('minState', [origin_user])
)
ENGINE = AggregatingMergeTree
PARTITION BY toYYYYMMDD(p_day)
ORDER BY (tag, tag_item)
SETTINGS index_granularity = 8192

【讨论】:

以上是关于clickhouse create table 异常:在查询中发现聚合函数 minState(origin_user) 位置错误的主要内容,如果未能解决你的问题,请参考以下文章

有没有可以在clickhouse中找到所有表索引的表?

Clickhouse 词典:为啥 CREATE DICTIONARY 需要数据库?

clickhouse创建物化视图数据来源是两张表该怎么写创建语句呢?

clickhouse[未解决] clickhouse Exception: Table is in readonly mode

clickhouse show tables

为啥 clickhouse 'DESCRIBE TABLE' 返回 4 或 5 列