Skip to content

Commit c889d40

Browse files
Merge pull request ClickHouse#79164 from ClickHouse/aggreation-keys-order
Preserve aggregation keys order after filter pushdown
2 parents 4d8bfa0 + 18e8fd4 commit c889d40

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

src/Processors/QueryPlan/Optimizations/filterPushDown.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,14 @@ addNewFilterStepOrThrow(QueryPlan::Node * parent_node, QueryPlan::Nodes & nodes,
152152
/// New filter column is the first one.
153153
String split_filter_column_name = split_filter.getOutputs().front()->result_name;
154154

155+
// If no new columns added, filter just used one of the input columns as-is and moved it to the front, move it back to keep aggregation key in order.
156+
if (const auto & input = node.children.at(0)->step->getOutputHeader(); split_filter.getOutputs().size() == input.columns())
157+
{
158+
auto pos = input.getPositionByName(split_filter_column_name);
159+
if (pos != 0)
160+
std::rotate(split_filter.getOutputs().begin(), split_filter.getOutputs().begin() + 1, split_filter.getOutputs().begin() + pos + 1);
161+
}
162+
155163
node.step = std::make_unique<FilterStep>(
156164
node.children.at(0)->step->getOutputHeader(), std::move(split_filter), std::move(split_filter_column_name), can_remove_filter);
157165

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
1 1 2
22
1 \N
33
1 1 2
4+
2
5+
1

tests/queries/0_stateless/01798_having_push_down.sql

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,11 @@ SELECT sum(c0 = 0), min(c0 + 1), sum(c0 + 2) FROM t_having
2525
GROUP BY c0 HAVING c0 = 0;
2626

2727
DROP TABLE t_having;
28+
29+
CREATE TABLE t_exact (c0 Bool, c1 Int) ENGINE = MergeTree() ORDER BY tuple();
30+
INSERT INTO TABLE t_exact (c0, c1) VALUES (FALSE, 1), (TRUE, 2);
31+
SELECT c1 FROM t_exact GROUP BY c1, c0 HAVING c0;
32+
DROP TABLE t_exact;
33+
34+
SELECT 1 FROM remote('127.0.0.{1,1}') GROUP BY (2, materialize(3)) HAVING materialize(3) SETTINGS group_by_use_nulls = true;
35+

0 commit comments

Comments
 (0)