Ir para o conteúdo

Lição 8 · Formulas

Window Functions

Use Sigma window functions for running totals, moving averages, ranks and previous values, and see why sort order and grouping levels change the results.

A window function looks at other rows while keeping every row in place. A running total, a rank or "the value from the previous month" are examples. In SQL these use an OVER clause. In Sigma you call a function by name, and the sort order and grouping levels of the table shape the result.

The main families

Need Functions
Running values CumulativeSum, CumulativeAvg, CumulativeMax, CumulativeCount
Rolling windows MovingSum, MovingAvg, MovingMax, MovingMin
Neighbors Lag, Lead, First, Last, Nth
Ranking Rank, RankDense, RankPercentile, RowNumber, Ntile
Gaps FillDown

Running totals

TEXT
CumulativeSum([Monthly Revenue])

The documentation warns that cumulative functions depend on row order: change the sort, and each row's result changes. A running total is only meaningful when the table is sorted by the thing it accumulates over, usually time.

In a grouped table, the running total is calculated separately within each higher grouping. If months are grouped under years, the total restarts each year. That is often what you want, but check it.

SQL Stand-in: a running total that restarts each year

Press Run (or Ctrl + Enter) to see the result here.

Moving averages

MovingAvg(column, above, [below]) averages a window around the current row. above is how many rows before the current row are included, and below is how many rows after it, with a default of zero:

TEXT
MovingAvg([Daily Orders], 6)

This covers the current row and up to six rows above it. It is a window of rows, not necessarily seven days. If a day has no data and therefore no row, the window reaches further back in time. Use a calendar table to give every day a row, with zero where "no orders" really means zero.

The first rows have fewer rows available, so their averages are based on less data. Consider hiding or marking them.

Previous and next values

Lag(value, offset, default) reads a value from an earlier row. The offset is 1 by default and must be a constant whole number above zero:

TEXT
Lag([Monthly Revenue])
[Monthly Revenue] / Lag([Monthly Revenue]) - 1

The second formula is month-over-month growth. For year-over-year with one row per month, you could use an offset of 12, only if every month is present and the table is sorted by month. Lead looks forward in a similar way.

Python Stand-in: moving average and growth in Python

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Ranking

Rank([column], [direction]) assigns a position. The direction is "asc" by default, so the smallest value gets rank 1. For "best seller is first", use "desc":

TEXT
Rank([Revenue], "desc")

With ties, equal values share a rank and the next ranks are skipped: three values tied for first are followed by rank 4. RankDense does not skip numbers. RowNumber numbers the rows. According to the documentation, nulls rank last when ascending and first when descending, so filter or label missing values before ranking.

Values (high to low) Rank RankDense
90 1 1
90 1 1
70 3 2

Windows and groups together

In a grouped table, the level where a window column sits matters. A rank at the product level inside a region grouping is meant to rank products within each region. Move the column to a different level and the meaning changes. After adding a window column, expand one group and check the numbers by hand.

Filters change windows

Filters limit the data a table works with. If you filter out earlier months, a running total starts at the first remaining month, and Lag has nothing earlier to read. If a report needs a year-to-date total while showing only the last three months, calculate with the full history first, for example in a parent element, and limit the display in a child.

When to push work upstream

If many workbooks need the same running or rolling metric, define it once in a data model, or compute it in the data platform with SQL window functions. See the SQL tutorial for the underlying ideas. One definition is easier to test than ten copies.

Common mistake: a user re-sorts a table by revenue and the running total now accumulates from the biggest month down. Nothing looks broken. Label such columns clearly and consider presenting them in a chart with time on the axis.

Verifying a window column

Window results are hard to check by eye, so use a small sample. Filter to one product or one region, sort by date, and calculate the first few values yourself. For a running total, each value should equal the previous total plus the current amount. For a moving average, add the rows in the window and divide by the number of rows used.

Then change the sort order on purpose and watch what happens. Seeing the numbers move helps you understand why the order matters, and reminds you to restore it before you publish.

Also test the borders between groups, where mistakes most often hide.

Choosing between a window and a grouping

If you want one row per month, group by month. If you want to keep the monthly rows and add a comparison, such as the previous month or a running total, add a window column to the grouped table. Mixing up these two ideas leads to confusing formulas. First decide what one row should mean, then decide which other rows each value needs to see.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What changes the result of a cumulative function?

    Cumulative functions walk the rows in order.
  2. 2. MovingAvg with above set to 6 covers what when enough rows exist?

    It is a row window. Missing dates would stretch it in time.
  3. 3. Values 90, 90, 70 ranked descending with Rank give which ranks?

    Rank skips numbers after ties; RankDense would give 1, 1, 2.
  4. 4. A filter removes older months. What can happen to Lag?

    Filtered rows are not available to the window.

Summary

  • Window functions use other rows while keeping each row.
  • Sort order and grouping level shape results.
  • Moving windows count rows, so fill missing dates when you need calendar windows.
  • Choose between Rank, RankDense and RowNumber on purpose.
  • Watch how filters change what a window can see.

Next: Groupings and Calculations

Seu progresso fica salvo neste navegador. Não precisa de conta.