You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Following on from #300, we can now implement window functions.
Much of the infrastructure has already been built by @aljazerzen , including using a similar construction to group. There will be some differences though, and it'll require some work in translation. It will be moderate-hard difficulty.
To answer your question from the PR @max-sixty: currently, we don't emit any "window frame clause" (that I meant with the first checkmark) so the queries default to database's default, which is, as you said, ROWS UNBOUNDED PRECEDING TO CURRENT ROW.
In my opinion, PRQL should default to the whole window (which may be limited to a group) or ROWS UNBOUNDED PRECEDING TO UNBOUNDED FOLLOWING.
If this would be the default behavior, does that mean that we should always emit the whole frame specification?
If neither the ORDER BY clause nor window frame clause are present, the window frame includes all rows in that partition.
For aggregate analytic functions, if the ORDER BY clause is present but the window frame clause is not, the following window frame clause is used by default: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
Yes, I think the default is always "everything up & including to the current row" for the functions that take window frame clauses.
In my opinion, PRQL should default to the whole window (which may be limited to a group) or ROWS UNBOUNDED PRECEDING TO UNBOUNDED FOLLOWING.
I can empathize with this. It might be confusing for people though; I think they're used to writing SUM(SALES) OVER (ORDER BY DATE) and getting a rolling sum. I'm not sure though; interested in others' thoughts here.
Doing the the end state has two distinct groups would mitigate this a bit, because the functions where window clauses matter would require them; i.e. this wouldn't be allowed:
from orders
sort date
derive sum_orders:(num_orders | sum) # What does `sum` mean here?
Instead, functions that take a window frame clause would also require one, so this would be required:
from orders
sort date
window ..current ( # [^1]
derive sum_orders:(num_orders | sum) # now it's hopefully obvious what `sum` is doing
)
...whereas lag wouldn't work like that, because there's no need for the window frame clause:
from orders
sort date
derive num_orders_last_week:(num_orders | lag 7)
TBC, that could be an end state — if you agree, we can make progress without everything being perfect initially.
This separates two things that are treated similarly in SQL, so it's more opinionated. Possibly that's confusing for hardcore SQL users, even if I think it makes conceptual sense.
If this would be the default behavior, does that mean that we should always emit the whole frame specification?
Completely up to the implementer. I would probably vote to not supply it, because it makes more readable SQL, and I think every DB has the same behavior, so we don't need to enforce any invariants at the PRQL level.
Footnotes
whatever syntax we use here; e.g. some punctuation for current↩
In some cases, one would want to have a sum over the whole window:
from departments
derive [total_cost: sum cost]derive [cost_percent: cost / total_cost *100]
That's a great case, I agree — doing over the whole window is the logical thing here.
Conceptually, we are taking a single value — the sum of cost — and dividing every row's cost by that. In SQL, we do that by creating a column with the same value in every row, and then using each value for each row's calc 1.
I think your plan is very reasonable indeed.
One clarification to the above around the default SQL behavior:
SELECT b / sum(b) over () defaults to the whole window, like we want
SELECT b / sum(b) over (order by date) defaults to ROWS UNBOUNDED PRECEDING TO UNBOUNDED FOLLOWING
I think for the second case, we should require a window transform, otherwise it's very confusing that adding a sort above a derive could have such a drastic effect.
I'll continue thinking about the broader case more.
One immediate thought is around how this composes. So if we wanted "percent of cost within department", we could have:
from departments
group dept (
derive [
total_cost: sum cost
cost_percent: cost / total_cost *100])
...and I think that could work quite well, and produce reasonable SQL.
If we wanted "percent of cost within each department for each sub-department" — i.e. we want to aggregate over one dimension and group by another, that's also possible:
from departments
group [dept, sub_dept](
aggregate (cost | sum))group dept (
derive [
total_cost: sum cost
cost_percent: cost / total_cost *100])
I realize this is a huge surface area. To the extent you're up for starting work on it, that would be amazing. Please feel free to take small bites; if someone tried to do a single PR with all of this, that might defeat them!
Footnotes
In xarray we do that by reducing to a single value, and then broadcasting that value when we combine the array during the calc. That seems conceptually nicer and more performant, because it's not repeating the same value n times, but there are no auto-joins in SQL since it doesn't know what dimensions are (Maybe a modeling layer like Malloy could help here?). If anyone is interested in a fuller explanation, I can make one. ↩
note for myself: in xarray, this would be similar, with da / da.groupby('dept').sum() and da.groupby('sub_dept').sum().pipe(lambda x: x / da.groupby('dept').sum()) respectively. PRQL has the advantage that the piping is much nicer. Xarray has the advantage that it would be easier to run this over an arbitrary number of extra dimensions, which would be preserved. But otherwise it's quite similar. ↩
I've changed sort so now it is reset at the start of each grouping.
Rationale behind this is that grouping is not stable - sorting you previously had is destroyed when rows are distributed among groups. After a discussion, it felt that this is the most natural way of doing it.
Also there is no need for doing sort [] after a window, because you don't want ORDER BY on the SELECT statement.
In SQL the default for window frame is (at least for Postgres and Spark):
Default frame specification depends on other aspects of a given window defintion:
if the ORDER BY clause is specified and the function accepts the frame specification, then the frame specification is defined by RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW,
otherwise the frame specification is defined by ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
expanding is intended to work on values (same as SQL default):
from days
sort day
window expanding:true (
derive [cumsum_orders = sum orders]
)
would produce
day
orders
cumsum_orders
2022-05-10
2
2
2022-05-11
3
5
2022-05-12
1
8
2022-05-12
2
8
2022-05-13
4
12
Note that day 2022-05-12 is duplicated for whatever reason, cumsum_orders has same value twice.
rolling guarantees same number of rows:
from days
sort day
window rolling:3 (
derive [avg_last_orders = (sum orders) / 3]
)
if the ORDER BY clause is specified and the function accepts the frame specification, then the frame specification is defined by RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW,
Note that day 2022-05-12 is duplicated for whatever reason, cumsum_orders has same value twice.
Ah, I see, I think this is the source of the confusion.
I think this is the difference between rows and range for unbounded preceding and current row — where there are duplicates, range includes equal rows.
You're completely correct that that is the default — I hadn't actually realized that — I guess I have been working with dates indexes without duplicates.
But this is isn't the meaning of expanding that I'm used to — at least it's not the meaning in pandas, which is the first place I learned about it (and maybe Uber's post, though inconclusive with timeseries as above).
What do you think about changing either the name or what expanding uses? Or is expanding actually better defined this way such that we want to deviate from pandas?
Do you think we should have a slightly different syntax for inclusive vs exclusive ranges, like rust has, then? My concern is that SQL ranges are by default inclusive; e.g. BETWEEN 0 and 3, or in 0..3 includes both 0 & 3, as does range:0..3
There are a few areas like this where it's difficult to completely upgrade SQL, because we can't see through to the data. So we can either separate off the parts we can — e.g. different approach to rows than other ranges — or compromises to their standards — e.g. just use inclusive for everything.
So, as I've said I used range for expanding, just because that's SQL default. But as I think about it more and as I tried to explain what range actually does, I found it's very hard to express and understand. rows is much more intuitive - at least for the cases I found.
So I agree we use rows for both rolling and expanding and leave range for people who want it.
Activity
aljazerzen commentedon Apr 29, 2022
I just merged a first step for this, which included a lot of preparation of AST nodes and our resolve steps: #435
TODO:
window ()contextaljazerzen commentedon Apr 29, 2022
To answer your question from the PR @max-sixty: currently, we don't emit any "window frame clause" (that I meant with the first checkmark) so the queries default to database's default, which is, as you said,
ROWS UNBOUNDED PRECEDING TO CURRENT ROW.In my opinion, PRQL should default to the whole window (which may be limited to a group) or
ROWS UNBOUNDED PRECEDING TO UNBOUNDED FOLLOWING.If this would be the default behavior, does that mean that we should always emit the whole frame specification?
SQL window frame defaults:
max-sixty commentedon Apr 29, 2022
Yes, I think the default is always "everything up & including to the current row" for the functions that take window frame clauses.
I can empathize with this. It might be confusing for people though; I think they're used to writing
SUM(SALES) OVER (ORDER BY DATE)and getting a rolling sum. I'm not sure though; interested in others' thoughts here.Doing the the end state has two distinct groups would mitigate this a bit, because the functions where window clauses matter would require them; i.e. this wouldn't be allowed:
Instead, functions that take a window frame clause would also require one, so this would be required:
1
...whereas
lagwouldn't work like that, because there's no need for the window frame clause:TBC, that could be an end state — if you agree, we can make progress without everything being perfect initially.
This separates two things that are treated similarly in SQL, so it's more opinionated. Possibly that's confusing for hardcore SQL users, even if I think it makes conceptual sense.
Completely up to the implementer. I would probably vote to not supply it, because it makes more readable SQL, and I think every DB has the same behavior, so we don't need to enforce any invariants at the PRQL level.
Footnotes
whatever syntax we use here; e.g. some punctuation for
current↩aljazerzen commentedon Apr 30, 2022
In some cases, one would want to have a sum over the whole window:
So I would go with "two distinct groups" approach, but would separate functions just by types of parameters:
max-sixty commentedon Apr 30, 2022
That's a great case, I agree — doing over the whole window is the logical thing here.
Conceptually, we are taking a single value — the sum of cost — and dividing every row's
costby that. In SQL, we do that by creating a column with the same value in every row, and then using each value for each row's calc 1.I think your plan is very reasonable indeed.
One clarification to the above around the default SQL behavior:
SELECT b / sum(b) over ()defaults to the whole window, like we wantSELECT b / sum(b) over (order by date)defaults toROWS UNBOUNDED PRECEDING TO UNBOUNDED FOLLOWINGI think for the second case, we should require a
windowtransform, otherwise it's very confusing that adding asortabove a derive could have such a drastic effect.I'll continue thinking about the broader case more.
One immediate thought is around how this composes. So if we wanted "percent of cost within department", we could have:
...and I think that could work quite well, and produce reasonable SQL.
If we wanted "percent of cost within each department for each sub-department" — i.e. we want to aggregate over one dimension and group by another, that's also possible:
2
I realize this is a huge surface area. To the extent you're up for starting work on it, that would be amazing. Please feel free to take small bites; if someone tried to do a single PR with all of this, that might defeat them!
Footnotes
In xarray we do that by reducing to a single value, and then broadcasting that value when we combine the array during the calc. That seems conceptually nicer and more performant, because it's not repeating the same value n times, but there are no auto-joins in SQL since it doesn't know what dimensions are (Maybe a modeling layer like Malloy could help here?). If anyone is interested in a fuller explanation, I can make one. ↩
note for myself: in xarray, this would be similar, with
da / da.groupby('dept').sum()andda.groupby('sub_dept').sum().pipe(lambda x: x / da.groupby('dept').sum())respectively. PRQL has the advantage that the piping is much nicer. Xarray has the advantage that it would be easier to run this over an arbitrary number of extra dimensions, which would be preserved. But otherwise it's quite similar. ↩[-]Implement window functions[/-][+]Window functions[/+]aljazerzen commentedon May 14, 2022
Reply @max-sixty for #478 (comment) regarding
Window order by
I've changed sort so now it is reset at the start of each
grouping.Rationale behind this is that grouping is not stable - sorting you previously had is destroyed when rows are distributed among groups. After a discussion, it felt that this is the most natural way of doing it.
Also there is no need for doing
sort []after a window, because you don't want ORDER BY on the SELECT statement.Here are unit tests for this change.
aljazerzen commentedon May 14, 2022
Reply to @max-sixty about #478 (comment) regarding
Expanding and rolling flags
In SQL the default for window frame is (at least for Postgres and Spark):
expandingis intended to work on values (same as SQL default):would produce
Note that day
2022-05-12is duplicated for whatever reason,cumsum_ordershas same value twice.rollingguarantees same number of rows:would produce
So documentation is correct in saying that:
expanding:trueis an alias forrange:..1rolling:xis an alias forrow:(-x+1)..1max-sixty commentedon May 14, 2022
Thanks, that's clear and I agree!
max-sixty commentedon May 14, 2022
Ah, I see, I think this is the source of the confusion.
I think this is the difference between
rowsandrangeforunbounded preceding and current row— where there are duplicates,rangeincludes equal rows.You're completely correct that that is the default — I hadn't actually realized that — I guess I have been working with dates indexes without duplicates.
But this is isn't the meaning of
expandingthat I'm used to — at least it's not the meaning in pandas, which is the first place I learned about it (and maybe Uber's post, though inconclusive with timeseries as above).What do you think about changing either the name or what
expandinguses? Or isexpandingactually better defined this way such that we want to deviate from pandas?max-sixty commentedon May 14, 2022
xref this question
aljazerzen commentedon May 15, 2022
Re #420 (comment)
So, as I've said I used
rangeforexpanding, just because that's SQL default. But as I think about it more and as I tried to explain what range actually does, I found it's very hard to express and understand.rowsis much more intuitive - at least for the cases I found.So I agree we use
rowsfor both rolling and expanding and leaverangefor people who want it.max-sixty commentedon May 15, 2022
Perfect, thanks! I'm happy to make the change IYL
aljazerzen commentedon May 16, 2022
Sure, go ahead
aljazerzen commentedon May 16, 2022
Closed by #501