diff --git a/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp b/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp index 3d7aa589225..c98535c8bb0 100644 --- a/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp +++ b/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp @@ -92,6 +92,11 @@ Block evaluateConstantGroupByKeysWithShardNumber( { Block res; + ColumnWithTypeAndName shard_num_col; + shard_num_col.type = std::make_shared(); + shard_num_col.column = shard_num_col.type->createColumnConst(0, shard_num); + shard_num_col.name = "_shard_num"; + if (auto group_by = query_ast->as().groupBy()) { for (const auto & elem : group_by->children) @@ -108,19 +113,20 @@ Block evaluateConstantGroupByKeysWithShardNumber( if (required_columns.size() != 1 || required_columns.count("_shard_num") == 0) continue; - auto type = std::make_shared(); - auto col = type->createColumnConst(1, shard_num); - std::string name = "_shard_num"; - - Block block({ColumnWithTypeAndName{col, type, name}}); - auto syntax_result = TreeRewriter(context).analyze(ast, {NameAndTypePair{name, type}}); - ExpressionAnalyzer(ast, syntax_result, context).getActions(true)->execute(block); + Block block({shard_num_col}); + auto syntax_result = TreeRewriter(context).analyze(ast, {NameAndTypePair{shard_num_col.name, shard_num_col.type}}); + ExpressionAnalyzer(ast, syntax_result, context).getActions(true, false)->execute(block); res.insert(block.getByName(key_name)); } } } + /// We always add _shard_num constant just in case. + /// For initial query it is considered as a column from table, and may be required by intermediate block. + if (!res.has(shard_num_col.name)) + res.insert(std::move(shard_num_col)); + return res; } diff --git a/tests/queries/0_stateless/01860_Distributed__shard_num_GROUP_BY.reference b/tests/queries/0_stateless/01860_Distributed__shard_num_GROUP_BY.reference index decc92f3ac0..fa0301316ae 100644 --- a/tests/queries/0_stateless/01860_Distributed__shard_num_GROUP_BY.reference +++ b/tests/queries/0_stateless/01860_Distributed__shard_num_GROUP_BY.reference @@ -14,3 +14,5 @@ 2 1 2 +1 1 +2 1 diff --git a/tests/queries/0_stateless/01860_Distributed__shard_num_GROUP_BY.sql b/tests/queries/0_stateless/01860_Distributed__shard_num_GROUP_BY.sql index 05b82ce4064..91215fd8ee6 100644 --- a/tests/queries/0_stateless/01860_Distributed__shard_num_GROUP_BY.sql +++ b/tests/queries/0_stateless/01860_Distributed__shard_num_GROUP_BY.sql @@ -10,3 +10,7 @@ SELECT _shard_num + dummy s, count() FROM remote('127.0.0.{1,2}', system.one) GR SELECT _shard_num FROM remote('127.0.0.{1,2}', system.one) ORDER BY _shard_num; SELECT _shard_num s FROM remote('127.0.0.{1,2}', system.one) ORDER BY _shard_num; + +SELECT _shard_num s, count() FROM remote('127.0.0.{1,2}', system.one) GROUP BY s order by s; + +select materialize(_shard_num), * from remote('127.{1,2}', system.one) limit 1 by dummy format Null;