Orthogonal treatment of groups (nee Window functions)
Edit — this issue evolved into a much broader discussion of how we do groups. The original message is below, and I've tried to summarize the current state towards the end of the issue so it's easier for others to engage.
More than half the people I speak with about PRQL tell me that window functions are painful in SQL and would be a great feature to add to PRQL. I put window funcitons in the examples in the Readme at first, since I had the same experience in SQL.
For clarity: a window / analytic / analytical function is a function that takes other rows as an input, but instead of aggregating over many rows, it creates a new value for every row. For example, a moving average or lag. In SQL it's represented by the OVER keyword.
I haven't thought about this enough, but wanted to post an issue so we could start thinking about how to do it. A couple of initial options:
- A separate pipeline, with the column at the end, and the function (
lagin this case) in the pipeline:
from prices
derive price_yesterday: (
window
by sec_id
sort date
lag 1
price
)
- A function with lots of named args, with the function
lagas a named arg (but how would this work for functions with 0 or >1 parameters?):
from prices
derive price_yesterday: (window by:sec_id sort:date lag:1 price)
- Eliminate
window— because we haveaggregate, we can't get confused aboutsum(foo) OVERandsum(foo), so possibly we don't need to havewindow:
from prices
derive price_yesterday: (price | lag rows:1 sort:date by:sec_id)
I don't think this is sufficiently thought through, and I'm sure these examples have inadequacies.
Here are some example queries we can use as cases: https://cloud.google.com/bigquery/docs/reference/standard-sql/analytic-function-concepts#get_the_most_popular_item_in_each_category
For anyone new to window functions (like I just was): good tutorial with illustrations
A nice observation that we could use in language design is that we have 3 types of functions:
- scalar functions, which map a single value to a single value (e.g.
FLOOR). They can be used in select and are applied to the whole column, on each value. - multi-variate functions, which map many values to a single value (e.g.
SUMorMIN). They can be used in aggregate and reduce each partition to one value. - vector functions, which map a many values to many values (eg.
RANKorLAG)/ They can be used as window functions in select and map column to column.
The problem is that when writing code you don't think about that. Is it advantageous if we force users to think about it?
If we would go this way, we would introduce new transform, let's say compute for lack of a better name:
from employees
compute rank(salary)
and with bounds and order:
from bills
sort issued_at
compute preceding:2 following:2 [
rolling_avg_amount: avg(amount)
]
sort number
Here I've used sort in two places, where the first affects only compute and the second affects the output.
Note that we would be the first languages I know to differentiate between select and compute in this way: dplyr, pandas and polars all have window functions within their selects.
The problem is that when writing code you don't think about that. Is it advantageous if we force users to think about it?
I definitely think there would be some benefits of structuring the language to consider types much more than SQL does — it could have a similar benefit to how your variable scoping now allows for knowing what's available to the language.
Ideally there's a synthesis where users don't need to think about it that much, but the compiler can still be helpful (not always possible :) )
vector functions, which map a many values to many values (eg.
RANKorLAG)/ They can be used as window functions in select and map column to column.
Yes great. Notably some, like AVG is both a reduction & vector function.
This is related to https://github.com/prql/prql/issues/54, which deals with a case similar to the "scalar" and "multi-variate" / (aka "reduction") functions.
Re the compute case, we do need some way to partition the values — see the by terms above. It could be as a transform of a window pipeline (the 1st case), an arg to a window function (2nd case), an arg to the vector function (3rd case), or something else.
Another option would be to make the partition primary, with something like a by arg to a map (still need to think about this more):
from employees
map by:title ( # or `compute`?
sort:salary
rank salary
)
One invariant that I think is important to keep in PRQL is that each transform should leave a valid result. Something like .group_by in pandas or dplyr doesn't do this (and in early discussion on PRQL, Hadley said this was one of his biggest regrets). So we shouldn't have:
from employees
window by:title # Invalid result here
rank salary
Notably some, like AVG is both a reduction & vector function.
Oh, that true, nice catch.
If we go this way, compiler will be able to infer the cardinality of the rows in resulting frame: only one, many or many for a set of keys. So we could actually provide correct typing for cases like #54, which is a huge plus.
Partitions
To me, the most consistent way of specifying partitions in compute/map would be by parameter, same as aggregate. The same as in your example.
For this approach the pro is that you can specify by only once, affecting many columns:
from employees
map by:title [ # or `compute`?
rank salary,
sum working_hours,
min salary,
max salary
]
Sort
I wouldnt mix inline pipelines into transforms, it can get confusing why some things have to be in a new line and some don't. Instead I would also put sort as a parameter to the map/compute:
from employees
map by:title sort:salary [ # or `compute`?
rank salary
]
Or, even better, infer it from the current state of the pipeline:
from employees
sort salary
map by:title [ # or `compute`?
rank salary
]
This way, there is less parameters users have to remember, while still being intuitive.
The downside is that the SQL output would also contain ORDER BY, which could only be avoided with putting another sort null at the end.
Naming
I don't like compute because it does not covey the "many to many" aspect of these functions.
I don't like map because in MapReduce, it means "one value to one value".
I don't like shuffle, because it does not convey that we are adding a new column.
I don't like partition, because in a lot of cases, there will be only one partition.
I don't like window, because it does not make sense for rank, quantile and many other functions.
Maybe something about fully-connected layer of a neural network? Something about vector functions? Something about new column for every row?
... is that each transform should leave a valid result
Fully agree.
If we go this way, compiler will be able to infer the cardinality of the rows in resulting frame: only one, many or many for a set of keys. So we could actually provide correct typing for cases like #54, which is a huge plus.
I strongly agree, this could be really good
I've been trying to think about what the OVER (PARTITION BY ...)s are doing conceptually. I started down a few paths, and came back to where I started, so there's no need to read the whole thing...
A reduction function is quite simple; it just reduced each group to a single row:
A vector function with a partition / grouping creates a mini-table table for each group. In SQL, because there's generally no nesting (i.e. everything is a flat 2D table) the by field gets "unnested":
An aside: in databases with nesting, the OVER (PARTITION BY foo) function is equivalent to doing:
ARRAY_AGG ... GROUP BY titleto get the arrays ofengineer -> [50,200], manager -> [120,130,150], etc- Run the vector function over each group (making the middle result)
- Unnest the
bysotitlefills down (making the final result)
So one option for this is:
- Use something like
groupormapornestto mean "build the groups", and it would take a quasi-pipeline to run over each group. A bit like thedplyr/spark/pandasAPI, but the function would be an argument to this rather than a subsequent transform (consistent with every transform leaving a correct result). - Use something like
computeto mean "apply this many-to-many function" (or another term, I know you say you don't like it, and I agree on the specific reason, though overall it seems decent relative to the other choices)
So that would mean we'd have something like:
from employees
group title (
sort title
compute [sum salary]
)
But if we do that, then we should be doing that for aggregates too:
from employees
group title (
aggregate [sum salary]
)
I can see the elegance of that. I'm obv hesitant to make a big change to the language at this point, and I'd need to sit on it for a couple of days before having a view. My sense is that the current model of doing aggregate by:title [] rather than than group title (aggregate [...]) is broadly equivalent and possibly easier to scan. The current approach is almost as orthogonal — we have aggregate for the reduction functions and compute (or similar) for the vector functions, not some long list. aggregate will also cover the case of making arrays.
So that brings us back to where we started!
Naming
I'm not sure on the word. I agree compute isn't ideal. calculate is basically the same. map in theory is nice — it is literally a mapping — and it's not always one-to-one. But maybe it has too much baggage. Its synonyms, like morph or functor are too weird. vec is too technical.
Sort
I get that you're less keen on pipelines-in-pipelines. I agree it's some mental overhead in simple cases, and so we shouldn't require them. But it does introduce a nice orthogonality. Say we want to "compute the two best selling items with a price higher than $100". It would be very nice to have:
from orders
{expression}
...for the case of the whole table, and:
from orders
compute by:country (
{expression}
)
...for the case of each group. Which supplying sort:foo or having the sort outside the compute doesn't achieve.
Indeed, note that in the current language, we have
from employees
aggregate [
(salary * 2 | sum) # possible, rather than `sum (salary * 2)`
]
...as a mini-pipeline.
BUT that said, I don't have a fully fleshed out proposal, and I'd be happy to go with the sort:foo for the moment. I prefer that to having sort outside the pipeline, since that specifies too much work — sorting the whole table rather than within each group.
The idea behind having sort in the outer pipeline instead of as a param, it that if you have two consecutive sorts, we can use only the last when translating to SQL. But if there is compute between the two sorts, it is affected by the first sort. This way, you reduce the number or params one has to remember. It can also think of the sorts as they have direct effect only the the conceptual model of current pipeline value, while only some of the sorts have to be translated into ORDER BY for SQL statement to produce the same result as the conceptual model.
(I hope that makes sense...)
About the group: I really like it.
As I've written here #9 we have common use-case where it would make sense for take to also have by parameters, because in-effect you want to group by some fields and take only the top row ordered by some other column.
So aggregate, compute and take need by parameter and two of them also need sorting. Unifying them under a group context seems an elegant solution.
But I would propose a few changes to the syntax:
Group:
from employees
group title (
sort salary
derive [r: rank] # compute is the same a derive within group context
select [count - r]
)
from employees
group title (
aggregate [sum salary]
)
from employees
group title (
sort salary order:desc
take 1 # this will return all columns, but only the row within a group that contains the highest salary
)
Group essentially introduces a new context where it is allowed to use aggregate, select, derive, sort and take. The normal context can use all transforms, but aggregate will always reduce to a single number and using sum in a select will produce a SELECT SUM(...) OVER ().
Two things:
- it would be attentive to the parser if we would replace parenthesis
(pipeline)with braces{pipeline}. It would make it much easier to parse inline and frame pipelines. - we should go and start writing queries with this change, before starting to write any code. Maybe rewrite all the examples and add new ones. If it does feel more natural, this is the way to go.
Great, I'm thinking about this. It would be quite a change!
It does seem to be quite nice, in both conceptual elegance and readability. You're right that to really understand we should write some examples.[^1]
Thanks for the examples, they're good. I agree with your points.
Much more narrowly:
The idea behind having sort
I very much understood the point the sort as the prior transformation — I just thought it was less coherent to have an integral part of the transformation outside of the main block. (it does fit with the pipeline notion though)
it would be attentive to the parser if we would replace parenthesis
(pipeline)with braces{pipeline}. It would make it much easier to parse inline and frame pipelines.
Would this be so (expression) is an parenthesized expression, but {pipeline} was required for all pipelines? We previously had that anything parenthized expression with line breaks was a pipeline (or more specifically any line break was a pipeline outside of a list or prior to a new statement like table).
[^1]: Though I am most of the way through a big update to how the documentation works with examples, hopefully I'll get that out so we don't have conflicts...
# https://www.databasestar.com/complex-sql-query-example
# https://www.databasestar.com/sample-bookstore-database/
from co:cust_order
join ol:order_line [co.order_id = ol.order_id]
derive [
order_month:s"DATE_FORMAT({co.order_date}, '%Y-%m')",
order_day:s"DATE_FORMAT({co.order_date}, '%Y-%m-%d')",
]
group [order_month, order_day] (
aggregate [
num_orders:s"COUNT(DISTINCT {co.order_id})"
num_books:count ol.book_id
total_price:sum ol.price
]
)
group [order_month] (
sort order_day order:asc
select running_total_num_books:sum num_books
)
group [] (
sort order_day order:asc
select num_books_last_week:lag num_books 7
)
sort order_day order:asc
How does it look?
Here's one pass:
- The main change is to not use
groupif we're not grouping by anything — my vision of this change was that we could make PRQL even more orthogonal by having functions within agroupscope operate on groups exactly the same way that they would operate on a full table without thegroupscope. But that means that it doesn't make sense to have an empty group.- I also wasn't sure whether I was understanding the intent of the existing query — what does the table look like after the
group [order_month]transform? Presumably it's no longer possible to get the previous week's sales at that point. Forgive me if I'm missing something!
- I also wasn't sure whether I was understanding the intent of the existing query — what does the table look like after the
- (Ironically given the subject of the issue), I'm still not sure how to specify window / analytic functions!
-
Should we have a specific transform for "functions which use other values in the column" — the definition of window functions — or are they just functions? i.e. is this OK:
derive num_books_last_month: lag num_books 1or do we need:
window (derive num_books_last_month: lag num_books 1)or:
derive ( num_books_last_month: window lag num_books 1 ) -
Where do we define window attributes? On the function? On the
window(or whatever name we use?- For a full list of things that can be in a window clause this reference was helpful: https://cloud.google.com/bigquery/docs/reference/standard-sql/analytic-function-concepts#def_window_frame
-
I don't like window, because it does not make sense for rank, quantile and many other functions.
I'm less averse to the name
windowafter thinking about it — it is a window over the column. It's not a moving window in the case of rank / quantile, but it says "look at the whole column rather than just my row" -
We could use designations like
rollingorexpanding, which would make describing common windows simpler. It would bring us to a synthesis of a pandas / spark specification and a SQL spec. -
I definitely think that unifying
group byandpartition byinto a single orthogonal concept would solve one of the existing pain points of SQL window functions.
-
- I made a couple of cosmetic changes / roadmap changes. (Possibly that's a distraction)
from co:cust_order
-join ol:order_line [co.order_id = ol.order_id]
+join ol:order_line [order_id]
derive [
- order_month:s"DATE_FORMAT({co.order_date}, '%Y-%m')",
- order_day:s"DATE_FORMAT({co.order_date}, '%Y-%m-%d')",
+ order_month:f"{co.order_date:%Y-%m}",
+ order_day:f"{co.order_date:%Y-%m-%d}",
]
group [order_month, order_day] (
aggregate [
num_orders: s"COUNT(DISTINCT {co.order_id})"
num_books: count ol.book_id
total_price: sum ol.price
]
)
group [order_month] (
sort order_day order:asc
select running_total_num_books: sum num_books
)
-group [] (
- sort order_day order:asc
- select num_books_last_week:lag num_books 7
- )
+sort order_day order:asc
+derive num_books_last_month: lag num_books 1 # Not sure about this
- sort order_day order:asc
Overall I think we're onto something but still need to pin down some of the details :). Your examples are v helpful in that regard.
One concern about the group approach is that it could make doing the simplest queries a bit more verbose. Say we just want to "select the sum of salary by country":
SQL:
SELECT
title,
SUM(salary)
FROM
employees
GROUP BY
title
Existing PRQL:
from employees
aggregate by:title [sum salary]
Proposed PRQL:
from employees
group title (
aggregate [sum salary]
)
But:
- It's not that much more verbose
- I generally think we should focus on making the difficult queries much more readable and coherent, rather than making simple queries a bit more concise.
To focus on the orthogonality point, there is a nice orthogonality to both:
Proposed PRQL — aggregation over groups
from employees
group title (
aggregate [sum salary]
)
Proposed PRQL — no groups:
from employees
aggregate [sum salary] # same transform outside a group, same effect
Proposed PRQL — using groups as partitions:
from employees
group title ( # No need for `GROUP BY` & `PARTITION BY`, similar to how we consolidate `WHERE` and `HAVING`
window [sum salary]
)
Oh, yeah I made a mistake:
from co:cust_order
join ol:order_line [order_id]
derive [
order_month:f"{co.order_date:%Y-%m}",
order_day:f"{co.order_date:%Y-%m-%d}",
]
group [order_month, order_day] (
aggregate [
num_orders: s"COUNT(DISTINCT {co.order_id})"
num_books: count ol.book_id
total_price: sum ol.price
]
)
group [order_month] (
sort order_day order:asc
- select running_total_num_books: sum num_books
+ derive running_total_num_books: sum num_books
)
sort order_day order:asc
derive num_books_last_month: lag num_books 1
I would change only your last example:
from employees
group title ( # No need for `GROUP BY` & `PARTITION BY`, similar to how we consolidate `WHERE` and `HAVING`
select [sum salary] # Or derive, depending on what you want
)
So rules would be as follows:
- select/derive
- can contain only scalar functions (FLOOR) and window functions (SUM, LAG, RANK)
- will not change the number of rows,
- when used within a group, they will produce PARTITION BY
- order by is determined by last preceding sort (within or outside of group)
- window is determined by parameters or select/derive[^1]
- aggregate
- can contain only aggregation functions (SUM)
- will reduce rows to the number of partitions (which is one when not used in a group)
Now:
-
there is no need for
window,computeormap -
select/derive/aggregateare completely orthogonal togroup -
this is OK:
derive num_books_last_month: (lag num_books 1) -
the query could be simplified even further, because we can move sort earlier in the pipeline:
...
group [order_month, order_day] (
aggregate [
num_orders: s"COUNT(DISTINCT {co.order_id})"
num_books: count ol.book_id
total_price: sum ol.price
]
)
+sort order_day order:asc
group [order_month] (
- sort order_day order:asc
derive running_total_num_books: sum num_books
)
-sort order_day order:asc
derive num_books_last_month: lag num_books 1
[^1]: could be a window context just as group, but what about window functions within group? I think having select/derive params is cleaner.
Yes, simple queries will be a bit more verbose, but complex queries will be easier to write and understand. I think that outweighs the cons by a lot.
We could use designations like
rollingorexpanding
I agree. But I believe that rows / range is quite nice formulation of what is possible. I would convert that to PRQL, by indexing current row with 0, one before with -1, one after with 1 and so on.
rows:-3..0-> "preceding 3 days, including current day"rows:-3..-1-> "preceding 3 days, excluding current day"rows:-3..3-> "preceding 3 days, current day and following 3 days" (equivalent torolling:3?)rows:..0-> "expanding" (equivalent toexpanding:true?)
from employees group title ( # No need for `GROUP BY` & `PARTITION BY`, similar to how we consolidate `WHERE` and `HAVING` select [sum salary] # Or derive, depending on what you want )
there is no need for
window,computeormap
select/derive/aggregateare completely orthogonal togroup
OK, I do really like this direction.
The rules for select/derive vs aggregate seem great.
It almost makes window functions too easy — they seem almost closer than normal sum functions etc. But this is no bad thing.
from employees group title ( sort salary order:desc take 1 )
Looking back over this, it's really so much nicer than the SQL alternatives (https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group !). And we can compile it whatever is most efficient without having to expose that.
Something that the proposal doesn't do is syntactically discriminate between:
- value -> value functions applied to a column, like
foo * 2 - column -> column functions ("window"), like
rank foo
That's probably OK though. There are no functions that can be ambiguous.
Maaaaybe we change the name of some of standard functions a bit, like sum -> rolling_sum. (I'm not sure this is a good idea).
Assuming I've got everything, I'm generally down with this. I'm interpreting it as "group by this, do that". It also feels in-line with the notion of "each line operates on the previous lines results". So, once we create a grouping, all operations should be on that grouping, until the grouping is over.
Final grammar then looking something like...
group [columns] (
operations
)
Allowed operations: aggregate derive sort select take with the limitations that @aljazerzen listed earlier...
select/derive
- can contain only scalar functions (FLOOR) and window functions (SUM, LAG, RANK)
- will not change the number of rows,
- when used within a group, they will produce PARTITION BY
- order by is determined by last preceding sort (within or outside of group)
- window is determined by parameters or select/derive1
aggregate
- can contain only aggregation functions (SUM)
- will reduce rows to the number of partitions (which is one when not used in a group)
Also, think this means aggregate will not exist outside of the group statement any more?
I'm really liking it too, I feel like this is 'thinking in PRQL'.
Do LAG/LEAD and friends need an OVER clause ? ( https://learnsql.com/blog/lead-and-lag-functions-in-sql/ seems to indiciate it does but I'm not sure ) , would that mean window functions can only occur inside group ?
In this example
group [order_month, order_day] (
aggregate [
num_orders: s"COUNT(DISTINCT {co.order_id})"
num_books: count ol.book_id
total_price: sum ol.price
]
)
sort order_day order:asc
group [order_month] (
derive running_total_num_books: sum num_books
)
derive num_books_last_month: lag num_books 1
Does that derive need to be in the group above it ? Or is it operating over every row returned
Also, think this means aggregate will not exist outside of the group statement any more?
@rbpatt2019 you can have an aggregates without a group , SELECT SUM(salary) so I think it's technically 'legal'
Synopsis of current discussion
I think we mostly agree that using group has some really nice properties — that we could have exactly the same expression in a group as outside of it, and it would have the same effect on the group as it would on the table.
For example, to calculate the total salary of the whole table:
from employees
aggregate [sum salary]
And to calculate the total salary of each title:
from employees
group title (
aggregate [sum salary] # same expression as above!
)
While it's a change, it's still similar to the existing approach, which we're proposed to remove — the proposal swaps the by for group, and puts the aggregate inside group:
from employees
aggregate by:title [sum salary] # old, would not work any longer.
The motivating example for this is https://github.com/prql/prql/issues/9 (demonstrating how useful it is for people to post cases!): get the employee with the highest salary for each title. Check out the issue for the amount of heat that this generates in SQL.
To get the employee with the highest salary across all employees, it's simply[^1]:
[^1]: Still working out the exact sort syntax here
from employees
sort salary order:desc
take 1
So to get for each group, it's just "put that expression in a group":
from employees
group title (
sort salary order:desc
take 1
)
It's not obvious how we'd do that with the existing syntax. In #9 I gave an idea of (slightly changed here to reflect the current example):
from employees
aggregate by:customer_id [
sort salary order:desc
take 1
]
...but why is the aggregate there? Is that a pipeline inside a list? The awkwardness here is a symptom of the lack of orthogonality.
Open questions
Windows
How does this framework apply to windows, the motivating topic for this discussion?[^2]. One proposal is that we don't need a window keyword, we would just have the window functions be functions on columns, so this would be rolling sum:
[^2]: FYI much of this took place on discord, I will be better at ensuring we post a summary to GH
from employees
sort salary
derive cumulative_salary: [sum salary]
And for PARTITION BY, this is very nice and orthogonal:
from employees
group title (
sort salary
derive cumulative_salary: [sum salary]
)
The downside of this is that it treats sum as an arbitrary function over the column. But that fails to capture the commonality between window functions — the window! sum in this context is summing over a series of windows — 0-n rows for row n. Other window functions (avg, corr, count, etc) use exactly the same window construction. So we can think of window functions as a function over a window which we define.
One idea is to apply a similar principle to window as we have to group, and again nest:
from employees
group title (
sort salary # sort moves outside the window, because it needs to be sorted for the window to make sense
window ..current ( # could define more on the window here
derive cumulative_salary: [sum salary]
)
)
without the partition this would be:
from employees
sort salary
window ..current (
derive cumulative_salary: [sum salary]
)
But is that too much nesting?
(And we can continue our orthogonality crusade by using a filter inside the window for QUALIFY.)
How do we think about () now?
We previously used parentheses to mean the standard mathematical "give precedence to operations inside". But here, it's more like "execute the contained pipeline on each object", in this case each groups.
It's more similar to jq's Update-assignment (can't seem to link to it, but search for update-assignment or |=). (FWIW I think we haven't used jq enough as a source of experience, there's a lot of wisdom and experience there.)
A couple of ways to think about this:
group(and maybewindow), take a pipeline as one of their arguments- We represent this operation with syntax e.g. (not suggesting the
<as a great option, a placeholder):
from employees
-group (
+group <(
sort salary order:desc
take 1
)
(@aljazerzen I'm v interested to know your perspective here — IIUC you weren't keen on relying on inline pipelines)
Is this just an awkward way of doing group_by?
Pandas / dplyr / spark / xarray all have:
(
df
.groupby("title")
.sum()
)
which would be possible to adopt with:
from employees
group title
aggregate [sum salary]
My central issue with this approach is that midway through the pipeline df.groupby("title"), we have something that doesn't evaluate to a valid result of data. If you know, you know, but it's unfamiliar, and particularly given our heavy reliance on pipelines, maintaining the invariant that every line in the pipeline returns a valid result is a great invariant.
Hadley Wickham called it one of his greatest regrets about dplyr in the HN discussion).
So I'd be keen to try and maintain this invariant.
Select / derive
Are there ambiguities on where select or derive should go?
e.g. should this be:
from employees
sort salary
window ..current (
derive cumulative_salary: [sum salary]
)
or
from employees
sort salary
derive cumulative_salary: window ..current (
[sum salary]
)
The advantage of the first is being able to to define lots of columns in the window, like we can for a group. The advantage of the second is that it's easy to understand the structure of the table by scanning the initial words — something that was heavily requested in the original HN discussion (when we didn't even have derive, just x: y as a full transform!)
Notably, SQL can't do multiple columns in a window. And we could allow window foo = as a definition at the top, in the same way we do for functions & tables now, and then let people use window foo inline; which could be helpful for complicated window definitions. Or allow these in functions.
Arrays
Do we need to think about how this interacts with arrays? I used to use this a lot when I worked with BigQuery a lot. Malloy (#71) have a good implementation of nested results. I think it's very tractable with the proposed approach — in place of group, we'd have nest (or similar), and instead of having the group value in n rows for n results, it would exist for only 1 row for n results.
So here TX is a single row, and then there's an array of 5 results in that row. If it were group, the TX would be 5 rows, each with 1 result.
(I am a big fan of Malloy and hoping they do really well, on this specific dimension I do think our design is better. But they have the implementation :) )
That's a lot — feel free to respond to individual points!
I'm a huge fan of the proposed group function. If there's a way to do it on the whole table, then that approach absolutely should be how you do it for a group. It just twigged as well that you could (running with the above example) have custom functions within group, so I think the following should be valid...
func take_first x = sort x order:dec | take 1
from employees
group title (
salary | take_first
)
So I think we get the benefit of increasing reusability, readability, and orthogonality in one go!
For syntax, I'm loath to use a syntax that bears any connotation of assignment. As I understand it, we aren't assigning anything. Rather, we are providing a key word that moves the "operate on the previous line's results" scope down a level - from the table to group and then back when closed. This feels much more like {} in rust and go to me. So I'll put forward...
from employees
- group title (
+ group title {
sort salary order:desc
take 1
- )
+ }
Commenting on the concerns about nested pipelines @aljazerzen and @max-sixty - my comment about scope above is why this doesn't bother me personally. I see this as not a nested pipeline, but a change in the level we operate at (ie down to group).
I'm not sure what the best way to handle window is though. The improvement for orthogonality (ie with derive and filter in a window clause) is strong to me. Or, at least I think it would be hypocritical to make it a motivating factor for group and not give it the same concern for window. I'll think on that a bit more...