This is an automated email from the ASF dual-hosted git repository.
cloud-fan pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 2a87edec2406 [SPARK-60124][SQL] Fix RewriteDistinctAggregates failure
on ListAgg with DISTINCT and FILTER
2a87edec2406 is described below
commit 2a87edec240692d49b3ce996e3b8fd54402880b2
Author: zahed9s <[email protected]>
AuthorDate: Fri Nov 13 14:56:41 2026 +0000
[SPARK-60124][SQL] Fix RewriteDistinctAggregates failure on ListAgg with
DISTINCT and FILTER
### What changes were proposed in this pull request?
In `RewriteDistinctAggregates`, aggregate functions with `SortOrder` in
their children (specifically `ListAgg` with `WITHIN GROUP (ORDER BY ...)`)
caused a `ClassCastException` during distinct rewrite when combined with
`FILTER` or when regular `ListAgg` is evaluated alongside other distinct
aggregates:
```
java.lang.ClassCastException: class
org.apache.spark.sql.catalyst.expressions.AttributeReference cannot be cast to
class org.apache.spark.sql.catalyst.expressions.SortOrder
at
org.apache.spark.sql.catalyst.expressions.aggregate.ListAgg.withNewChildrenInternal(collect.scala:1051)
at
org.apache.spark.sql.catalyst.optimizer.RewriteDistinctAggregates.patchAggregateFunctionChildren(RewriteDistinctAggregates.scala:262)
```
This occurred because:
1. `SortOrder` extends `Expression` with `Unevaluable`, but Catalyst treats
`orderExpressions` as part of `ListAgg.children`.
2. `RewriteDistinctAggregates` treated `SortOrder` directly as an
unfoldable child expression, causing `Expand` to project `SortOrder` (an
`Unevaluable` expression).
3. `patchAggregateFunctionChildren` mapped `af.children` with
`attrs(c).getOrElse(c)`, replacing the `SortOrder` itself with an
`AttributeReference`. When `ListAgg.withNewChildrenInternal` cast
`newChildren.drop(2)` back to `SortOrder`, it threw `ClassCastException`.
This PR fixes the issue by:
1. Introducing an `evalChildren` helper in `RewriteDistinctAggregates` that
unpacks `SortOrder.children` to operate on evaluable expressions when
determining foldability, grouping sets, and projecting attributes.
2. In `patchAggregateFunctionChildren`, unwrapping `SortOrder`, replacing
only its child expressions with rewritten attributes, and preserving the
`SortOrder` wrapper.
3. In `SparkStrategies.Aggregation`, extracting a shared
`evalDistinctChildren` helper that unwraps `SortOrder` before filtering
foldables for both the `distinctAggChildSets` sanity check and
`distinctExpressions` key extraction. This ensures distinct aggregates that
differ only in `WITHIN GROUP` ordering plan cleanly through the single-distinct
path and constant distinct arguments equal to the delimiter are not erroneously
substituted.
### Why are the changes needed?
Queries that use `LISTAGG(DISTINCT ...) WITHIN GROUP (ORDER BY ...) FILTER
(...)` or regular `LISTAGG(...) WITHIN GROUP (ORDER BY ...)` alongside distinct
aggregates fail during query planning with an internal `ClassCastException`.
Furthermore, without aligning `SparkStrategies.Aggregation`, grouped queries
combining `COUNT(DISTINCT s)` with ordered `LISTAGG(DISTINCT s)` or queries
with delimiter equal to a constant distinct argument would hit internal planner
errors.
### Does this PR introduce _any_ user-facing change?
Yes.
- **Previous behavior:** Queries such as `LISTAGG(DISTINCT s) WITHIN GROUP
(ORDER BY s) FILTER (WHERE ...)` or non-distinct ordered `LISTAGG` alongside
multiple distinct aggregates over different columns failed during query
planning with an internal `ClassCastException` (`AttributeReference cannot be
cast to SortOrder`). Grouped queries combining `COUNT(DISTINCT s)` with ordered
`LISTAGG(DISTINCT s)` failed in planning with an internal analyzer/planner
error.
- **New behavior:** These queries now plan and execute successfully,
returning the expected aggregated results.
### How was this patch tested?
- Added unit tests in `RewriteDistinctAggregatesSuite`.
- Added end-to-end execution tests in `DataFrameAggregateSuite`.
### Was this patch authored or co-authored using generative AI tooling?
No.
Closes #59460 from zahed1994/SPARK-60124-listagg-distinct-filter.
Authored-by: zahed9s <[email protected]>
Signed-off-by: Wenchen Fan <[email protected]>
skip-checks: true
---
.../optimizer/RewriteDistinctAggregates.scala | 30 ++-
.../optimizer/RewriteDistinctAggregatesSuite.scala | 47 ++++-
.../spark/sql/execution/SparkStrategies.scala | 16 +-
.../apache/spark/sql/DataFrameAggregateSuite.scala | 206 +++++++++++++++++++++
4 files changed, 282 insertions(+), 17 deletions(-)
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala
index a79898115271..e00ad9cee36c 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala
@@ -204,6 +204,13 @@ import org.apache.spark.util.collection.Utils
* techniques.
*/
object RewriteDistinctAggregates extends Rule[LogicalPlan] {
+ private def evalChildren(exprs: Seq[Expression]): Seq[Expression] = {
+ exprs.flatMap {
+ case so: SortOrder => so.children
+ case other => Seq(other)
+ }
+ }
+
private def mustRewrite(
distinctAggs: Seq[AggregateExpression],
groupingExpressions: Seq[Expression]): Boolean = {
@@ -212,8 +219,13 @@ object RewriteDistinctAggregates extends Rule[LogicalPlan]
{
// foldable, we need to rewrite the query, e.g. SELECT COUNT(DISTINCT 1).
Without this case,
// non-grouping aggregation queries with distinct aggregate expressions
will be incorrectly
// handled by the aggregation strategy, causing wrong results when working
with empty tables.
+ // An ordered distinct aggregate whose arguments and WITHIN GROUP keys are
all constants
+ // (e.g. listagg(DISTINCT 'x', ',') WITHIN GROUP (ORDER BY 'x')) counts as
all-foldable here
+ // because evalChildren unwraps SortOrder before checking foldability. The
rule must not rely
+ // on the planner keeping a SortOrder-wrapped constant as the
single-distinct key, and the
+ // extra Expand cost for such queries is accepted to guarantee correct
empty-table results.
distinctAggs.exists(_.filter.isDefined) || (groupingExpressions.isEmpty &&
- distinctAggs.exists(_.aggregateFunction.children.forall(_.foldable)))
+ distinctAggs.exists(e =>
evalChildren(e.aggregateFunction.children).forall(_.foldable)))
}
private def mayNeedtoRewrite(a: Aggregate): Boolean = {
@@ -237,7 +249,8 @@ object RewriteDistinctAggregates extends Rule[LogicalPlan] {
private def groupDistinctAggs(
aggExpressions: Seq[AggregateExpression]): Map[ExpressionSet,
Seq[AggregateExpression]] = {
aggExpressions.filter(_.isDistinct).groupBy { e =>
- val unfoldableChildren =
ExpressionSet(e.aggregateFunction.children.filter(!_.foldable))
+ val unfoldableChildren = ExpressionSet(
+ evalChildren(e.aggregateFunction.children).filter(!_.foldable))
if (unfoldableChildren.nonEmpty) {
// Only expand the unfoldable children
unfoldableChildren
@@ -248,7 +261,7 @@ object RewriteDistinctAggregates extends Rule[LogicalPlan] {
// count(distinct 1) will be explained to count(1) after the rewrite
function.
// Generally, the distinct aggregateFunction should not run
// foldable TypeCheck for the first child.
- ExpressionSet(e.aggregateFunction.children.take(1))
+ ExpressionSet(evalChildren(e.aggregateFunction.children).take(1))
}
}
}
@@ -285,7 +298,12 @@ object RewriteDistinctAggregates extends Rule[LogicalPlan]
{
def patchAggregateFunctionChildren(
af: AggregateFunction)(
attrs: Expression => Option[Expression]): AggregateFunction = {
- val newChildren = af.children.map(c => attrs(c).getOrElse(c))
+ val newChildren = af.children.map {
+ case so: SortOrder =>
+ so.withNewChildren(so.children.map(c => attrs(c).getOrElse(c)))
+ case c =>
+ attrs(c).getOrElse(c)
+ }
af.withNewChildren(newChildren).asInstanceOf[AggregateFunction]
}
@@ -362,7 +380,7 @@ object RewriteDistinctAggregates extends Rule[LogicalPlan] {
val operators = expressions.map { e =>
val af = e.aggregateFunction
val condition = e.filter.flatMap(distinctAggFilterAttrLookup.get)
- val naf = if (af.children.forall(_.foldable)) {
+ val naf = if (evalChildren(af.children).forall(_.foldable)) {
af
} else {
patchAggregateFunctionChildren(af) { x =>
@@ -386,7 +404,7 @@ object RewriteDistinctAggregates extends Rule[LogicalPlan] {
val regularAggExprs = aggExpressions
.filter(e => !e.isDistinct && e.children.exists(!_.foldable))
val regularAggFunChildren = regularAggExprs
- .flatMap(_.aggregateFunction.children.filter(!_.foldable))
+ .flatMap(e =>
evalChildren(e.aggregateFunction.children).filter(!_.foldable))
val regularAggFilterAttrs = regularAggExprs.flatMap(_.filterAttributes)
val regularAggChildren = (regularAggFunChildren ++
regularAggFilterAttrs).distinct
val regularAggChildAttrMap =
regularAggChildren.map(expressionAttributePair)
diff --git
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregatesSuite.scala
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregatesSuite.scala
index 2f5360b50df8..bafbeac9dcca 100644
---
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregatesSuite.scala
+++
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregatesSuite.scala
@@ -18,12 +18,20 @@ package org.apache.spark.sql.catalyst.optimizer
import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.dsl.plans._
-import org.apache.spark.sql.catalyst.expressions.{Add, AttributeReference,
CaseWhen, Cast, Coalesce, Divide, EvalMode, Exists, Expression, GetMapValue,
GetStructField, If, InSubquery, ListQuery, Literal, Lower, Not,
NumericEvalContext, Or, Rand, Round, Substring}
-import
org.apache.spark.sql.catalyst.expressions.aggregate.{AggregateExpression,
CollectSet, Count, Sum}
+import org.apache.spark.sql.catalyst.expressions.{
+ Add, Ascending, AttributeReference, CaseWhen, Cast, Coalesce, Divide,
EvalMode, Exists,
+ Expression, GetMapValue, GetStructField, If, InSubquery, ListQuery, Literal,
Lower, Not,
+ NumericEvalContext, Or, Rand, Round, SortOrder, Substring
+}
+import org.apache.spark.sql.catalyst.expressions.aggregate.{
+ AggregateExpression, CollectSet, Count, ListAgg, Sum
+}
import org.apache.spark.sql.catalyst.plans.PlanTest
import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, Expand,
LocalRelation, LogicalPlan}
import org.apache.spark.sql.internal.SQLConf
-import org.apache.spark.sql.types.{DoubleType, IntegerType, MapType,
StringType, StructField, StructType}
+import org.apache.spark.sql.types.{
+ DoubleType, IntegerType, MapType, StringType, StructField, StructType
+}
class RewriteDistinctAggregatesSuite extends PlanTest {
val nullInt = Literal(null, IntegerType)
@@ -127,6 +135,38 @@ class RewriteDistinctAggregatesSuite extends PlanTest {
}
}
+ test("SPARK-60124: listagg with distinct and filter") {
+ val relation = LocalRelation($"s".string, $"keep".int)
+ val input = relation
+ .select(
+ ListAgg(
+ child = $"s",
+ delimiter = Literal("|"),
+ orderExpressions = Seq(SortOrder($"s", Ascending))
+ ).toAggregateExpression(
+ isDistinct = true,
+ filter = Some($"keep" === 1)
+ ).as("rendered")
+ ).analyze
+ val rewrite = RewriteDistinctAggregates(input)
+ assert(rewrite.resolved)
+ }
+
+ test("SPARK-60124: regular listagg alongside distinct aggregates") {
+ val relation = LocalRelation($"a".int, $"b".int, $"s".string)
+ val input = relation
+ .groupBy($"a")(
+ countDistinct($"b").as("agg1"),
+ countDistinct($"a").as("agg2"),
+ ListAgg(
+ child = $"s",
+ delimiter = Literal("|"),
+ orderExpressions = Seq(SortOrder($"s", Ascending))
+ ).toAggregateExpression(isDistinct = false).as("rendered")
+ ).analyze
+ val rewrite = RewriteDistinctAggregates(input)
+ assert(rewrite.resolved)
+ }
//
---------------------------------------------------------------------------
// COUNT(DISTINCT IF/CASE) canonicalization (SPARK-56898)
//
---------------------------------------------------------------------------
@@ -840,3 +880,4 @@ class RewriteDistinctAggregatesSuite extends PlanTest {
}
}
}
+
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
index ba139316ed1f..2b3c42e70a43 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
@@ -625,8 +625,14 @@ abstract class SparkStrategies extends
QueryPlanner[SparkPlan] {
ae.aggregateFunction.isInstanceOf[PythonAggregate]) =>
val (functionsWithDistinct, functionsWithoutDistinct) =
aggExpressions.partition(_.isDistinct)
+ def evalDistinctChildren(ae: aggregate.AggregateExpression):
Seq[Expression] = {
+ ae.aggregateFunction.children.flatMap {
+ case s: SortOrder => s.children
+ case e => Seq(e)
+ }.filterNot(_.foldable)
+ }
val distinctAggChildSets = functionsWithDistinct.map { ae =>
- ExpressionSet(ae.aggregateFunction.children.filterNot(_.foldable))
+ ExpressionSet(evalDistinctChildren(ae))
}.distinct
if (distinctAggChildSets.length > 1) {
// This is a sanity check. We should not reach here when we have
multiple distinct
@@ -659,13 +665,7 @@ abstract class SparkStrategies extends
QueryPlanner[SparkPlan] {
// to be [COUNT(DISTINCT foo), MAX(DISTINCT foo)], but
// [COUNT(DISTINCT bar), COUNT(DISTINCT foo)] is disallowed
because those two distinct
// aggregates have different column expressions.
- val distinctExpressions =
- functionsWithDistinct.head.aggregateFunction.children
- .filterNot(_.foldable)
- .map {
- case s: SortOrder => s.child
- case e => e
- }
+ val distinctExpressions =
evalDistinctChildren(functionsWithDistinct.head)
val normalizedNamedDistinctExpressions = distinctExpressions.map {
e =>
// Ideally this should be done in `NormalizeFloatingNumbers`,
but we do it here
// because `distinctExpressions` is not extracted during logical
phase.
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/DataFrameAggregateSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/DataFrameAggregateSuite.scala
index f9a9febaf783..de514acb31cc 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/DataFrameAggregateSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/DataFrameAggregateSuite.scala
@@ -5761,7 +5761,213 @@ class DataFrameAggregateSuite extends SharedSparkSession
assert(outType.precision == 24 && outType.scale == 6,
s"expected DecimalType(24, 6) from un-rewritten AVG, got $outType")
}
+
+ test("SPARK-60124: listagg(DISTINCT ...) with FILTER") {
+ val df = Seq(
+ ("b", 1), ("a", 1), ("a", 1), (null.asInstanceOf[String], 1), ("c", 0)
+ ).toDF("s", "keep")
+
+ checkAnswer(
+ df.selectExpr("listagg(DISTINCT s, '|') WITHIN GROUP (ORDER BY s) FILTER
(WHERE keep = 1)"),
+ Seq(Row("a|b"))
+ )
+ checkAnswer(
+ df.selectExpr(
+ "count(DISTINCT keep)",
+ "listagg(DISTINCT s, '|') WITHIN GROUP (ORDER BY s) FILTER (WHERE keep
= 1)"
+ ),
+ Seq(Row(2, "a|b"))
+ )
+ // Regular listagg alongside two distinct groups forces
RewriteDistinctAggregates to execute
+ checkAnswer(
+ df.selectExpr(
+ "count(DISTINCT keep)",
+ "count(DISTINCT s)",
+ "listagg(s, '|') WITHIN GROUP (ORDER BY s)"
+ ),
+ Seq(Row(2, 3, "a|a|b|c"))
+ )
+ }
+
+ test("SPARK-60124: listagg(DISTINCT ...) merged single-distinct path without
FILTER") {
+ val df = Seq(
+ ("b", 1), ("a", 1), ("a", 1), (null.asInstanceOf[String], 1), ("c", 0)
+ ).toDF("s", "keep")
+
+ // count(DISTINCT s) with listagg(DISTINCT s) without FILTER
+ checkAnswer(
+ df.selectExpr(
+ "count(DISTINCT s)",
+ "listagg(DISTINCT s, '|') WITHIN GROUP (ORDER BY s)"
+ ),
+ Seq(Row(3, "a|b|c"))
+ )
+
+ // listagg(DISTINCT s) ASC alongside listagg(DISTINCT s) DESC without
FILTER
+ checkAnswer(
+ df.selectExpr(
+ "listagg(DISTINCT s, '|') WITHIN GROUP (ORDER BY s ASC)",
+ "listagg(DISTINCT s, '|') WITHIN GROUP (ORDER BY s DESC)"
+ ),
+ Seq(Row("a|b|c", "c|b|a"))
+ )
+ }
+
+ test("SPARK-60124: listagg with ORDER BY expression differing from
aggregated column") {
+ // 1. Regular listagg with ORDER BY separate column alongside two distinct
groups
+ // Note: 'b' has ord=1 and 'a' has ord=2 so ord order ("b" then "a") is
opposite
+ // alphabetical order ("a" then "b"). This verifies ord is used, not s.
+ val df1 = Seq(
+ ("b", 1, 1), ("a", 1, 2), ("a", 1, 2), (null.asInstanceOf[String], 1,
3), ("c", 0, 4)
+ ).toDF("s", "keep", "ord")
+
+ checkAnswer(
+ df1.selectExpr(
+ "count(DISTINCT keep)",
+ "count(DISTINCT s)",
+ "listagg(s, '|') WITHIN GROUP (ORDER BY ord ASC)"
+ ),
+ Seq(Row(2, 3, "b|a|a|c"))
+ )
+
+ checkAnswer(
+ df1.selectExpr(
+ "count(DISTINCT keep)",
+ "count(DISTINCT s)",
+ "listagg(s, '|') WITHIN GROUP (ORDER BY ord DESC)"
+ ),
+ Seq(Row(2, 3, "c|a|a|b"))
+ )
+
+ // 2. Distinct listagg ordered by i itself; it aggregates CAST(i AS
STRING), so order is numeric
+ // Numerically 9 < 10 ("9,10"), whereas lexicographically "10" < "9"
("10,9").
+ val df2 = Seq((9, 1), (10, 1), (2, 0)).toDF("i", "keep")
+
+ checkAnswer(
+ df2.selectExpr(
+ "listagg(DISTINCT i, ',') WITHIN GROUP (ORDER BY i) FILTER (WHERE keep
= 1)"
+ ),
+ Seq(Row("9,10"))
+ )
+ }
+
+ test("SPARK-60124: grouped distinct aggregates with constant WITHIN GROUP
keys") {
+ val df = Seq((1, "x"), (1, "y"), (2, "z")).toDF("k", "v")
+
+ // 1. count(DISTINCT 'a') next to listagg(DISTINCT 'a', ',') WITHIN GROUP
(ORDER BY 'a')
+ checkAnswer(
+ df.groupBy("k").agg(
+ expr("count(DISTINCT 'a')"),
+ expr("listagg(DISTINCT 'a', ',') WITHIN GROUP (ORDER BY 'a')")
+ ),
+ Seq(Row(1, 1, "a"), Row(2, 1, "a"))
+ )
+
+ // 2. Reversed order so either aggregate can supply the planner's
single-distinct key
+ checkAnswer(
+ df.groupBy("k").agg(
+ expr("listagg(DISTINCT 'a', ',') WITHIN GROUP (ORDER BY 'a')"),
+ expr("count(DISTINCT 'a')")
+ ),
+ Seq(Row(1, "a", 1), Row(2, "a", 1))
+ )
+
+ // 3. Unordered listagg(DISTINCT 'a', ',') next to ordered
listagg(DISTINCT 'a', ',')
+ checkAnswer(
+ df.groupBy("k").agg(
+ expr("listagg(DISTINCT 'a', ',')"),
+ expr("listagg(DISTINCT 'a', ',') WITHIN GROUP (ORDER BY 'a')")
+ ),
+ Seq(Row(1, "a", "a"), Row(2, "a", "a"))
+ )
+
+ // 4. Constant key originating from a subquery column projected as a
literal
+ checkAnswer(
+ df.selectExpr("k", "'a' AS c").groupBy("k").agg(
+ expr("count(DISTINCT c)"),
+ expr("listagg(DISTINCT c, ',') WITHIN GROUP (ORDER BY c)")
+ ),
+ Seq(Row(1, 1, "a"), Row(2, 1, "a"))
+ )
+
+ // 5. listagg argument equal to delimiter with listagg listed first
+ checkAnswer(
+ df.groupBy("k").agg(
+ expr("listagg(DISTINCT ',', ',') WITHIN GROUP (ORDER BY ',')"),
+ expr("count(DISTINCT ',')")
+ ),
+ Seq(Row(1, ",", 1), Row(2, ",", 1))
+ )
+
+ // 6. ordered listagg listed before unordered listagg with argument equal
to delimiter
+ checkAnswer(
+ df.groupBy("k").agg(
+ expr("listagg(DISTINCT ',', ',') WITHIN GROUP (ORDER BY ',')"),
+ expr("listagg(DISTINCT ',', ',')")
+ ),
+ Seq(Row(1, ",", ","), Row(2, ",", ","))
+ )
+
+ // 7. lone grouped listagg with argument equal to delimiter
+ checkAnswer(
+ df.groupBy("k").agg(
+ expr("listagg(DISTINCT ',', ',') WITHIN GROUP (ORDER BY ',')")
+ ),
+ Seq(Row(1, ","), Row(2, ","))
+ )
+
+ // 8. projected literal column equal to delimiter
+ checkAnswer(
+ df.selectExpr("k", "',' AS c").groupBy("k").agg(
+ expr("listagg(DISTINCT c, ',') WITHIN GROUP (ORDER BY c)"),
+ expr("count(DISTINCT c)")
+ ),
+ Seq(Row(1, ",", 1), Row(2, ",", 1))
+ )
+ }
+
+ test("SPARK-60124: global constant-only ordered DISTINCT LISTAGG on empty
and non-empty input") {
+ val emptyDf = Seq.empty[(Int, String)].toDF("v", "s")
+ val nonEmptyDf = Seq((1, "a"), (2, "b"), (3, "c")).toDF("v", "s")
+
+ // On empty input: returns NULL alone and NULL with sum(v)
+ checkAnswer(
+ emptyDf.selectExpr("listagg(DISTINCT 'x', ',') WITHIN GROUP (ORDER BY
'x')"),
+ Seq(Row(null))
+ )
+ checkAnswer(
+ emptyDf.selectExpr("listagg(DISTINCT 'x', ',') WITHIN GROUP (ORDER BY
'x')", "sum(v)"),
+ Seq(Row(null, null))
+ )
+ checkAnswer(
+ emptyDf.selectExpr("listagg(DISTINCT ',', ',') WITHIN GROUP (ORDER BY
',')"),
+ Seq(Row(null))
+ )
+ checkAnswer(
+ emptyDf.selectExpr("listagg(DISTINCT ',', ',') WITHIN GROUP (ORDER BY
',')", "sum(v)"),
+ Seq(Row(null, null))
+ )
+
+ // On non-empty input: returns 'x' alone and 'x' with sum(v) = 6
+ checkAnswer(
+ nonEmptyDf.selectExpr("listagg(DISTINCT 'x', ',') WITHIN GROUP (ORDER BY
'x')"),
+ Seq(Row("x"))
+ )
+ checkAnswer(
+ nonEmptyDf.selectExpr("listagg(DISTINCT 'x', ',') WITHIN GROUP (ORDER BY
'x')", "sum(v)"),
+ Seq(Row("x", 6))
+ )
+ checkAnswer(
+ nonEmptyDf.selectExpr("listagg(DISTINCT ',', ',') WITHIN GROUP (ORDER BY
',')"),
+ Seq(Row(","))
+ )
+ checkAnswer(
+ nonEmptyDf.selectExpr("listagg(DISTINCT ',', ',') WITHIN GROUP (ORDER BY
',')", "sum(v)"),
+ Seq(Row(",", 6))
+ )
+ }
}
+
case class B(c: Option[Double])
case class A(b: Option[B])
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]