jayzhan211 commented on code in PR #27773:
URL: https://github.com/apache/datafusion/pull/27773#discussion_r4719603728
##########
datafusion/sql/src/select.rs:
##########
@@ -564,6 +564,28 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
}
Some(Distinct::Distinct) => {
let plan = self.try_process_unnest(plan,
select_exprs_post_aggr)?;
+ if let LogicalPlan::Projection(projection) = &plan {
+ // DISTINCT exposes only the projection's output columns.
+ //
+ // SELECT DISTINCT a + 1 AS v FROM t ORDER BY a + 1;
+ //
+ // The sort input has v, so trying to resolve t.a would
fail.
+ // Match a + 1 against the aliased projection expression
and
+ // use v as the sort key, as in ORDER BY v.
+ for sort in &mut order_by_rex {
+ if matches!(sort.expr, Expr::Column(_)) {
+ continue;
+ }
Review Comment:
@TinyMurky thanks for the fix! This `Expr::Column` skip is what keeps a bare
output name from matching an input column with the same name, but no test fails
if it's removed. Without it, `SELECT DISTINCT column1 AS column2, column2 AS
column1 FROM (VALUES (1, 20), (2, 10)) ORDER BY column1` returns `(1, 20), (2,
10)` instead of `(2, 10), (1, 20)`. Could you add a comment saying why, and
this case to `order.slt`?
```suggestion
// A bare column may name an output column whose
name an input
// column in another expression shares, e.g. ORDER
BY column1 in
// SELECT DISTINCT column1 AS column2, column2 AS
column1.
if matches!(sort.expr, Expr::Column(_)) {
continue;
}
```
```
# ORDER BY column1 names the output column1 (input column2), not the input
# column1 that the first SELECT expression reads
query II
SELECT DISTINCT column1 AS column2, column2 AS column1
FROM (VALUES (1, 20), (2, 10))
ORDER BY column1;
----
2 10
1 20
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]