Merge pull request #39354 from ClickHouse/window-order-by

Respect ORDER BY clause in window functions
This commit is contained in:
Alexey Milovidov 2022-09-19 09:22:37 +03:00 committed by GitHub
commit b01f5bdca8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 63 additions and 1 deletions

View File

@ -1988,6 +1988,23 @@ 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);
if (auto * function = order_expression->as<ASTFunction>();
function && (function->is_window_function || function->compute_after_window_functions))
continue;
const String & column_name = order_expression->getColumnName();
chain.getLastStep().addRequiredOutput(column_name);
}
}
before_window = chain.getLastActions();
finalize_chain(chain);
@ -2007,7 +2024,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());

View File

@ -0,0 +1,37 @@
-- { 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
SELECT count() OVER (ORDER BY number + 1) + 1 as foo FROM numbers(10)
ORDER BY foo;
2
3
4
5
6
7
8
9
10
11

View File

@ -0,0 +1,9 @@
-- { 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;
SELECT count() OVER (ORDER BY number + 1) + 1 as foo FROM numbers(10)
ORDER BY foo;