Window

For each row, the segment over which the pipeline is applied is determined by one of:

  • , which takes a range of rows relative to the current row position.
    • 0 references the current row.
  • range, which takes a range of values relative to current row value.

For ease of use, there are two flags that override rows or range:

  • expanding:true is an alias for rows:..0. A sum using this window is also known as “cumulative sum”.
  • rolling:n is an alias for row:(-n+1)..0, where n is an integer. This will include n last values, including current row. An average using this window is also knows as a Simple Moving Average.

  1. from employees
  2. group employee_id (
  3. sort month
  4. window rolling:12 (
  5. derive [trail_12_m_comp = sum paycheck]
  6. )
  7. )

  1. *,
  2. SUM(paycheck) OVER (
  3. PARTITION BY employee_id
  4. ORDER BY
  5. month ROWS BETWEEN 11 PRECEDING AND CURRENT ROW
  6. ) AS trail_12_m_comp
  7. FROM
  8. employees

  1. SELECT
  2. *,
  3. AVG(value) OVER (
  4. ORDER BY
  5. day ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING
  6. ) AS centered_weekly_average,
  7. SUM(value) OVER (
  8. PARTITION BY order_month
  9. ORDER BY
  10. day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  11. ) AS monthly_running_total
  12. FROM
  13. orders

If you use window functions without window transform, they will be applied to the whole table. Unlike in SQL, they will remain window functions and will not trigger aggregation.

PRQL

  1. from employees
  2. sort age
  3. derive rnk = rank

SQL

PRQL

  1. from employees
  2. sort age
  3. derive rnk = rank
  4. )

SQL

  1. SELECT
  2. *,
  3. RANK() OVER (
  4. PARTITION BY department
  5. ORDER BY
  6. age ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
  7. ) AS rnk
  8. FROM
  9. employees

There is no limitaions where windowed expressions can be used:

  1. WITH table_1 AS (
  2. SELECT
  3. *,
  4. AVG(salary) OVER () AS _expr_0
  5. FROM
  6. employees
  7. )
  8. SELECT
  9. *
  10. FROM
  11. table_1 AS table_0
  12. salary < _expr_0