> ## Documentation Index
> Fetch the complete documentation index at: https://lightdash-mintlify-cccf65ca.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Rolling window

> Rolling windows, or lookbacks, calculate metrics like rolling averages using the current row combined with N previous rows. This can be useful for smoothing out volatile time series data to better understand long term trends.

[Just gimme the code! <Icon icon="bug" iconType="solid" />](#here’s-the-sql-you-can-copy-paste-to-calculate-rolling-windows)

Here's an example of a rolling window:

<Frame>
  <img src="https://mintcdn.com/lightdash-mintlify-cccf65ca/8jl62BZ1l-L8wRh0/images/guides/table-calculations/table-calculation-sql-templates/rolling-window-53f41043a0eb91ed5c240e5c72190323.jpg?fit=max&auto=format&n=8jl62BZ1l-L8wRh0&q=85&s=bbc35f19371deed71dca176bf09af7c0" width="638" height="357" data-path="images/guides/table-calculations/table-calculation-sql-templates/rolling-window-53f41043a0eb91ed5c240e5c72190323.jpg" />
</Frame>

And here's the SQL used in the table calculation:

```sql theme={null}
SUM(${dbt_orders.count_distinct_order_id}) OVER (
  ORDER BY
    ${dbt_orders.order_date_week}
  ROWS BETWEEN 3 PRECEDING AND CURRENT ROW
) /
  SUM(${dbt_orders.count_distinct_user_id}) OVER (
    ORDER BY
      ${dbt_orders.order_date_week}
    ROWS BETWEEN 3 PRECEDING AND CURRENT ROW
  )
```

The SQL used for calculating rolling windows has at least two bits, with an optional third:

* `first_column_I_want_to_sum` is the column with the values you want to add up (sometimes this is an average)
* `column_I_want_to_order_by` is the column you want to order by when defining your lookback window
* `N` is the number of previous rows you want to include in your calculation (don't forget the current row is included, so for a four week lookback window, we'll use N=3)
* `second_column_I_want_to_sum` is optional, another column with values you want to add up to compare to your first column, like when calculating averages (which is how we use it in this example)

### Here's the SQL you can copy-paste to calculate rolling windows

Make sure you swap out the columns AND choose a number value for `N`.

```sql theme={null}
SUM(${table.column_I_want_to_sum}) OVER (
  ORDER BY
    ${table.column_I_want_to_order_by}
  ROWS BETWEEN N PRECEDING AND CURRENT ROW
) /
  SUM(${table.second_column_I_want_to_sum}) OVER (
    ORDER BY
      ${table.column_I_want_to_order_by}
    ROWS BETWEEN N PRECEDING AND CURRENT ROW
  )
```
