Respect ORDER BY clause in window functions

This commit is contained in:
Dmitry Novik 2022-07-18 16:42:38 +00:00
parent b4eae94889
commit cf30f08937
3 changed files with 45 additions and 1 deletions

View File

@ -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<ASTOrderByElement>();
ASTPtr order_expression = ast->children.at(0);
const String & column_name = order_expression->getColumnName();
chain.getLastStep().addRequiredOutput(column_name);
}
}
before_window = chain.getLastActions(); before_window = chain.getLastActions();
finalize_chain(chain); finalize_chain(chain);
@ -2038,7 +2052,6 @@ ExpressionAnalysisResult::ExpressionAnalysisResult(
// produced the expressions required to calculate window functions. // produced the expressions required to calculate window functions.
// They are not needed in the final SELECT result. Knowing the correct // They are not needed in the final SELECT result. Knowing the correct
// list of columns is important when we apply SELECT DISTINCT later. // 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) for (const auto & child : select_query->select()->children)
{ {
step.addRequiredOutput(child->getColumnName()); step.addRequiredOutput(child->getColumnName());

View File

@ -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

View File

@ -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;