Skip to content

Commit 61e8a5d

Browse files
authored
add order by for last value (#15695)
1 parent 0b01fdf commit 61e8a5d

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

datafusion/functions-aggregate/src/first_last.rs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ use datafusion_macros::user_doc;
5252
use datafusion_physical_expr_common::sort_expr::LexOrdering;
5353

5454
create_func!(FirstValue, first_value_udaf);
55+
create_func!(LastValue, last_value_udaf);
5556

5657
/// Returns the first value in a group of values.
5758
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 {
6768
}
6869
}
6970

71+
/// Returns the last value in a group of values.
72+
pub fn last_value(expression: Expr, order_by: Option<Vec<SortExpr>>) -> Expr {
73+
if let Some(order_by) = order_by {
74+
last_value_udaf()
75+
.call(vec![expression])
76+
.order_by(order_by)
77+
.build()
78+
// guaranteed to be `Expr::AggregateFunction`
79+
.unwrap()
80+
} else {
81+
last_value_udaf().call(vec![expression])
82+
}
83+
}
84+
7085
#[user_doc(
7186
doc_section(label = "General Functions"),
7287
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 {
939954
}
940955
}
941956

942-
make_udaf_expr_and_func!(
943-
LastValue,
944-
last_value,
945-
"Returns the last value in a group of values.",
946-
last_value_udaf
947-
);
948-
949957
#[user_doc(
950958
doc_section(label = "General Functions"),
951959
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.",

0 commit comments

Comments
 (0)