Skip to content

[SPARK-42346][SQL] Rewrite distinct aggregates after subquery merge #39887

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ class SparkOptimizer(
Batch("InjectRuntimeFilter", FixedPoint(1),
InjectRuntimeFilter) :+
Batch("MergeScalarSubqueries", Once,
MergeScalarSubqueries) :+
MergeScalarSubqueries,
RewriteDistinctAggregates) :+
Batch("Pushdown Filters from PartitionPruning", fixedPoint,
PushDownPredicates) :+
Batch("Cleanup filters that cannot be pushed down", Once,
Expand Down
25 changes: 25 additions & 0 deletions sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2598,4 +2598,29 @@ class SubquerySuite extends QueryTest
Row("aa"))
}
}

test("SPARK-42346: Rewrite distinct aggregates after merging subqueries") {
withTempView("t1") {
Seq((1, 2), (3, 4)).toDF("c1", "c2").createOrReplaceTempView("t1")

checkAnswer(sql(
"""
|SELECT
| (SELECT count(distinct c1) FROM t1),
| (SELECT count(distinct c2) FROM t1)
|""".stripMargin),
Row(2, 2))

// In this case we don't merge the subqueries as `RewriteDistinctAggregates` kicks off for the
// 2 subqueries first but `MergeScalarSubqueries` is not prepared for the `Expand` nodes that
// are inserted by the rewrite.
checkAnswer(sql(
"""
|SELECT
| (SELECT count(distinct c1) + sum(distinct c2) FROM t1),
| (SELECT count(distinct c2) + sum(distinct c1) FROM t1)
|""".stripMargin),
Row(8, 6))
}
}
}