Apache DataFusion SQL Query Engine
add order by for last value (#15695)
Jay Zhan61e8a5d0d658
diff --git a/datafusion/functions-aggregate/src/first_last.rs b/datafusion/functions-aggregate/src/first_last.rsindex 6465436375..ec8c440b77 100644--- a/datafusion/functions-aggregate/src/first_last.rs+++ b/datafusion/functions-aggregate/src/first_last.rs@@ -52,6 +52,7 @@ use datafusion_macros::user_doc;use datafusion_physical_expr_common::sort_expr::LexOrdering;create_func!(FirstValue, first_value_udaf);+create_func!(LastValue, last_value_udaf);/// Returns the first value in a group of values.pub fn first_value(expression: Expr, order_by: Option<Vec<SortExpr>>) -> Expr {@@ -67,6 +68,20 @@ pub fn first_value(expression: Expr, order_by: Option<Vec<SortExpr>>) -> Expr {}}+/// Returns the last value in a group of values.+pub fn last_value(expression: Expr, order_by: Option<Vec<SortExpr>>) -> Expr {+ if let Some(order_by) = order_by {+ last_value_udaf()+ .call(vec![expression])+ .order_by(order_by)+ .build()+ // guaranteed to be `Expr::AggregateFunction`+ .unwrap()+ } else {+ last_value_udaf().call(vec![expression])+ }+}+#[user_doc(doc_section(label = "General Functions"),description = "Returns the first element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group.",@@ -939,13 +954,6 @@ impl Accumulator for FirstValueAccumulator {}}-make_udaf_expr_and_func!(- LastValue,- last_value,- "Returns the last value in a group of values.",- last_value_udaf-);-#[user_doc(doc_section(label = "General Functions"),description = "Returns the last element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group.",