Skip to content

Window functions #420

Closed
Closed

Description

@max-sixty

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.

Activity

  1. aljazerzen commented on Apr 29, 2022

    @aljazerzen
    Member

    I just merged a first step for this, which included a lot of preparation of AST nodes and our resolve steps: #435

    TODO:

    • window frames via window () context
    • declare functions like SUM as both aggregate and window
  2. aljazerzen commented on Apr 29, 2022

    @aljazerzen
    Member

    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:

    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

    The default framing option is RANGE UNBOUNDED PRECEDING, which is the same as RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW

  3. max-sixty commented on Apr 29, 2022

    @max-sixty
    MemberAuthor

    SQL window frame defaults:

    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
    )

    1

    ...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

    1. whatever syntax we use here; e.g. some punctuation for current ↩

  4. aljazerzen commented on Apr 30, 2022

    @aljazerzen
    Member

    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]
    

    So I would go with "two distinct groups" approach, but would separate functions just by types of parameters:

    func (sum col:: Column | Window)::Column | number = body
    
    func (lag col:: Column)::Column = body
  5. max-sixty commented on Apr 30, 2022

    @max-sixty
    MemberAuthor

    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
      ]
    )

    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

    1. 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. ↩

    2. 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. ↩

  6. added this to the 0.2 milestone on May 1, 2022
  7. changed the title [-]Implement window functions[/-] [+]Window functions[/+] on May 1, 2022
  8. aljazerzen commented on May 14, 2022

    @aljazerzen
    Member

    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.

  9. aljazerzen commented on May 14, 2022

    @aljazerzen
    Member

    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):

    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]
    )
    

    would produce

    day orders cumsum_orders
    2022-05-10 1
    2022-05-11 3
    2022-05-12 1 1.6667
    2022-05-12 2 2
    2022-05-13 4 2.3333

    So documentation is correct in saying that:

    • expanding:true is an alias for range:..1
    • rolling:x is an alias for row:(-x+1)..1
  10. max-sixty commented on May 14, 2022

    @max-sixty
    MemberAuthor

    Window order by

    Thanks, that's clear and I agree!

  11. max-sixty commented on May 14, 2022

    @max-sixty
    MemberAuthor

    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?

  12. max-sixty commented on May 14, 2022

    @max-sixty
    MemberAuthor

    xref this question

    Wonderful reference and explanation.

    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.

    WDYT?

  13. aljazerzen commented on May 15, 2022

    @aljazerzen
    Member

    Re #420 (comment)

    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.

  14. max-sixty commented on May 15, 2022

    @max-sixty
    MemberAuthor

    So I agree we use rows for both rolling and expanding and leave range for people who want it.

    Perfect, thanks! I'm happy to make the change IYL

  15. aljazerzen commented on May 16, 2022

    @aljazerzen
    Member

    Sure, go ahead

  16. aljazerzen commented on May 16, 2022

    @aljazerzen
    Member

    Closed by #501

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions