diff --git a/src/Interpreters/ExpressionAnalyzer.cpp b/src/Interpreters/ExpressionAnalyzer.cpp index 23258c60099..9b7e947c848 100644 --- a/src/Interpreters/ExpressionAnalyzer.cpp +++ b/src/Interpreters/ExpressionAnalyzer.cpp @@ -2019,6 +2019,20 @@ ExpressionAnalysisResult::ExpressionAnalysisResult( } } + // Here we need to set order by expression as required output to avoid + // their removal from the ActionsDAG. + const auto * select_query = query_analyzer.getSelectQuery(); + if (select_query->orderBy()) + { + for (auto & child : select_query->orderBy()->children) + { + auto * ast = child->as(); + ASTPtr order_expression = ast->children.at(0); + const String & column_name = order_expression->getColumnName(); + chain.getLastStep().addRequiredOutput(column_name); + } + } + before_window = chain.getLastActions(); finalize_chain(chain); @@ -2038,7 +2052,6 @@ ExpressionAnalysisResult::ExpressionAnalysisResult( // produced the expressions required to calculate window functions. // They are not needed in the final SELECT result. Knowing the correct // list of columns is important when we apply SELECT DISTINCT later. - const auto * select_query = query_analyzer.getSelectQuery(); for (const auto & child : select_query->select()->children) { step.addRequiredOutput(child->getColumnName()); diff --git a/tests/queries/0_stateless/02366_window_function_order_by.reference b/tests/queries/0_stateless/02366_window_function_order_by.reference new file mode 100644 index 00000000000..166573ea3f1 --- /dev/null +++ b/tests/queries/0_stateless/02366_window_function_order_by.reference @@ -0,0 +1,25 @@ +-- { echoOn } +SELECT groupArray(tuple(value)) OVER () +FROM (select number value from numbers(10)) +ORDER BY value ASC; +[(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)] +[(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)] +[(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)] +[(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)] +[(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)] +[(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)] +[(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)] +[(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)] +[(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)] +[(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)] +SELECT count() OVER (ORDER BY number + 1) FROM numbers(10) ORDER BY number; +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 diff --git a/tests/queries/0_stateless/02366_window_function_order_by.sql b/tests/queries/0_stateless/02366_window_function_order_by.sql new file mode 100644 index 00000000000..86fd6ed2f24 --- /dev/null +++ b/tests/queries/0_stateless/02366_window_function_order_by.sql @@ -0,0 +1,6 @@ +-- { echoOn } +SELECT groupArray(tuple(value)) OVER () +FROM (select number value from numbers(10)) +ORDER BY value ASC; + +SELECT count() OVER (ORDER BY number + 1) FROM numbers(10) ORDER BY number;