diff --git a/CHANGELOG.md b/CHANGELOG.md index 1439c549236f..03418474f391 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,9 @@ **Fixes**: +- `sort` step before an `aggregate` step no longer requires its columns in order + to avoid a group by clause error. (@julien-pinchelimouroux, #5347) + **Documentation**: **Web**: @@ -21,6 +24,8 @@ **New Contributors**: +- @julien-pinchelimouroux, with #5347 + ## 0.13.4 — 2025-03-26 0.13.4 is a small bugfix release. diff --git a/prqlc/prqlc/src/sql/pq/anchor.rs b/prqlc/prqlc/src/sql/pq/anchor.rs index e4f9c13a3774..d2d697ddb35b 100644 --- a/prqlc/prqlc/src/sql/pq/anchor.rs +++ b/prqlc/prqlc/src/sql/pq/anchor.rs @@ -500,7 +500,10 @@ pub(super) fn get_requirements( Super(Filter(expr)) | SqlTransform::Join { filter: expr, .. } => { CidCollector::collect(expr.clone()) } - Super(Sort(sorts)) => sorts.iter().map(|s| s.column).collect(), + // Aggregations require that all selected columns be wrapped in aggregate functions (e.g., SUM, COUNT). + Super(Sort(sorts)) if !following.contains("Aggregate") => { + sorts.iter().map(|s| s.column).collect() + } Super(Take(rq::Take { range, .. })) => { let mut cids = Vec::new(); if let Some(e) = &range.start { diff --git a/prqlc/prqlc/tests/integration/sql.rs b/prqlc/prqlc/tests/integration/sql.rs index 9c01260aef8d..385769f3c8b3 100644 --- a/prqlc/prqlc/tests/integration/sql.rs +++ b/prqlc/prqlc/tests/integration/sql.rs @@ -1308,6 +1308,21 @@ fn test_sorts_03() { "); } +#[test] +fn test_sort_before_aggregate() { + assert_snapshot!((compile(r#" + from a + sort a.col + aggregate { result = sum a.col_to_agg } + "# + ).unwrap()), @r" + SELECT + COALESCE(SUM(col_to_agg), 0) AS result + FROM + a + "); +} + #[test] fn test_numbers() { let query = r###"