Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

n() ignores ordering in window_frame #700

Closed
mattcane opened this issue Aug 27, 2021 · 0 comments · Fixed by #797
Closed

n() ignores ordering in window_frame #700

mattcane opened this issue Aug 27, 2021 · 0 comments · Fixed by #797
Labels
feature a feature request or enhancement func trans 🌍 Translation of individual functions to SQL

Comments

@mattcane
Copy link

When using n() in an ordered window frame the ordering seems to be ignored when it's translated to SQL. Use case would be knowing how many rows are actually included in a rolling sum/average/etc.

mf <- memdb_frame(
  tibble(
    grp = c(rep('a',4), rep('b', 5)),
    order = seq(1,9),
    val = seq(11,19)
  )
)

mf %>%
  group_by(
    grp
  ) %>%
  # Arrange by order
  window_order(order) %>%
  # Calc rolling 2 row sum
  window_frame(-2,-1) %>%
  mutate(
    roll_last_2_sum = sum(val),
    # Get number of rows in frame
    n_rows_in_frame = n()
  ) %>%
  show_query()

# Output is:
# SELECT `grp`, `order`, `val`, SUM(`val`) OVER (PARTITION BY `grp` ORDER BY `order` ROWS BETWEEN 2 PRECEDING AND 1 PRECEDING) AS `roll_last_2_sum`, COUNT(*) OVER (PARTITION BY `grp`) AS `n_rows_in_frame`

# Output should be:
# SELECT `grp`, `order`, `val`, SUM(`val`) OVER (PARTITION BY `grp` ORDER BY `order` ROWS BETWEEN 2 PRECEDING AND 1 PRECEDING) AS `roll_last_2_sum`, COUNT(*) OVER (PARTITION BY `grp` ORDER BY `order` ROWS BETWEEN 2 PRECEDING AND 1 PRECEDING) AS `n_rows_in_frame`
@hadley hadley added feature a feature request or enhancement func trans 🌍 Translation of individual functions to SQL labels Dec 8, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature a feature request or enhancement func trans 🌍 Translation of individual functions to SQL
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants