diff --git a/dbms/src/Interpreters/ExpressionAnalyzer.cpp b/dbms/src/Interpreters/ExpressionAnalyzer.cpp index 33d47b6de79..5c9b31c2c70 100644 --- a/dbms/src/Interpreters/ExpressionAnalyzer.cpp +++ b/dbms/src/Interpreters/ExpressionAnalyzer.cpp @@ -849,8 +849,19 @@ bool ExpressionAnalyzer::appendLimitBy(ExpressionActionsChain & chain, bool only getRootActions(select_query->limitBy(), only_types, step.actions); + NameSet aggregated_names; + for (const auto & column : aggregated_columns) + { + step.required_output.push_back(column.name); + aggregated_names.insert(column.name); + } + for (const auto & child : select_query->limitBy()->children) - step.required_output.push_back(child->getColumnName()); + { + auto child_name = child->getColumnName(); + if (!aggregated_names.count(child_name)) + step.required_output.push_back(std::move(child_name)); + } return true; } diff --git a/dbms/tests/queries/0_stateless/00409_shard_limit_by.reference b/dbms/tests/queries/0_stateless/00409_shard_limit_by.reference index 8aa9b8f42c0..f928ed6ad22 100644 --- a/dbms/tests/queries/0_stateless/00409_shard_limit_by.reference +++ b/dbms/tests/queries/0_stateless/00409_shard_limit_by.reference @@ -24,3 +24,4 @@ 101 101 102 +1 diff --git a/dbms/tests/queries/0_stateless/00409_shard_limit_by.sql b/dbms/tests/queries/0_stateless/00409_shard_limit_by.sql index 430b29376a1..97748d3e077 100644 --- a/dbms/tests/queries/0_stateless/00409_shard_limit_by.sql +++ b/dbms/tests/queries/0_stateless/00409_shard_limit_by.sql @@ -32,4 +32,7 @@ SELECT 1 as one FROM remote('127.0.0.{2,3}', system.one) LIMIT 1 BY one; -- Distributed LIMIT BY with LIMIT SELECT toInt8(number / 5 + 100) AS x FROM remote('127.0.0.1', system.numbers) LIMIT 2 BY x LIMIT 5; +-- Distributed LIMIT BY with ORDER BY non-selected column +SELECT 1 AS x FROM remote('127.0.0.{2,3}', system.one) ORDER BY dummy LIMIT 1 BY x; + DROP TABLE IF EXISTS limit_by;