Advanced DAX in Power BI: Window Functions and Calculation Groups
Introduction
Advanced DAX in Power BI helps you write measures that respond predictably to filters. This DP-600 lesson covers iterators, variables, window functions, calculation groups, dynamic format strings and field parameters. The examples show how to keep the model reusable while making its calculations easier to verify.
Learning objectives
- Use VAR and RETURN to name and reuse expressions evaluated in the same context.
- Explain filter context, row context and context transition, and choose between aggregators and iterators.
- Filter tables with
FILTER,ALL,ALLSELECTED,KEEPFILTERSandCALCULATETABLE. - Use window functions (
INDEX,OFFSET,WINDOW,RANK,ROWNUMBER) and information functions (ISBLANK,ISFILTERED,HASONEVALUE,SELECTEDVALUE,USERPRINCIPALNAME). - Create calculation groups, dynamic format strings and field parameters.
1. Evaluation contexts in one page
Start with the context in which the expression runs. For a runnable query with a scoped measure, see KQL and DAX query examples in Fabric. For the model that propagates the filters, review Power BI semantic model design and relationships.
| Context | Created by | Effect |
|---|---|---|
| Filter context | Slicers, rows and columns of a visual, filters, CALCULATE |
Restricts the rows of tables before the expression is evaluated |
| Row context | Calculated columns, iterators (SUMX, FILTER, ADDCOLUMNS) |
Gives access to the current row's values, one row at a time |
Context transition. Inside a row context, CALCULATE (and any measure reference, which is wrapped in an implicit CALCULATE) converts the current row into filters. This is why SUMX ( DimCustomer, [Total Sales] ) returns each customer's sales and adds them up: for each customer row, the measure is evaluated with that customer as a filter.
CALCULATE ( <expression>, <filter1>, <filter2> ... ) modifies the filter context. A Boolean filter such as DimProduct[Color] = "Red" replaces an existing ordinary filter on that column by default. Other columns can still filter the result. Separate filter arguments are evaluated before they are applied to the expression. KEEPFILTERS intersects with the existing filter instead.
Red Sales = CALCULATE ( [Total Sales], DimProduct[Color] = "Red" )
All Sales = CALCULATE ( [Total Sales], ALL ( DimProduct ) )
Share of All = DIVIDE ( [Total Sales], [All Sales] )2. Variables
Use VAR to bind a value and RETURN to produce the measure result. The value is evaluated at most once for that declaration in its evaluation context. A variable declared inside an iterator can have a different value for each row.
Sales vs Prior Year % =
VAR CurrentSales = [Total Sales]
VAR PriorSales =
CALCULATE ( [Total Sales], SAMEPERIODLASTYEAR ( DimDate[Date] ) )
RETURN
IF ( NOT ISBLANK ( PriorSales ), DIVIDE ( CurrentSales - PriorSales, PriorSales ) )Benefits:
| Benefit | Why |
|---|---|
| Performance | Reusing a value can avoid repeated work in the same context |
| Readability | Names such as PriorSales document intent |
| Debugging | You can RETURN a variable to inspect an intermediate value |
| Correctness | The value is frozen before a later CALCULATE changes the filter context |
A common trap: a variable captured before a CALCULATE keeps the old context.
Wrong Share =
VAR S = [Total Sales]
RETURN DIVIDE ( S, CALCULATE ( S, ALL ( DimProduct ) ) ) -- 1 when S is nonzero because both arguments use the same valueCALCULATE ( S, ALL ( DimProduct ) ) cannot change S because S was evaluated earlier. The correct form calls the measure inside the CALCULATE.
Example. A margin measure refers to [Revenue] and [Cost] four times in nested IF branches. Rewriting with VAR Revenue = [Revenue] and VAR Cost = [Cost] shortens it and can avoid repeated evaluation when both references need the same context. Measure the actual query cost.
3. Aggregators and iterators
An aggregator (SUM, AVERAGE, MIN, MAX, COUNT) works on one column. An iterator (SUMX, AVERAGEX, MINX, MAXX, COUNTX, RANKX, CONCATENATEX) evaluates an expression row by row over a table and then aggregates.
| Need | Use |
|---|---|
| Sum of a stored column | SUM ( FactSales[NetAmount] ) |
| Sum of a per-row calculation | SUMX ( FactSales, FactSales[Quantity] * FactSales[UnitPrice] ) |
| Average of a per-customer total | AVERAGEX ( VALUES ( DimCustomer[CustomerKey] ), [Total Sales] ) |
| Count of distinct values | DISTINCTCOUNT ( FactSales[CustomerKey] ) |
| Maximum of a measure by group | MAXX ( VALUES ( DimProduct[Category] ), [Total Sales] ) |
Worked example: average sales per customer
Statement. FactSales has one row per order line. One customer bought two lines at €30 and €70. A second bought one line at €60. Management asks for the average sales per customer with sales in the selected period.
Reasoning.
AVERAGEof the amount column gives the average order line, because the grain of the table is one line.- "Per customer" needs customers as the unit: first compute total sales per customer, then average those totals.
- VALUES returns the customer keys visible in the dimension. AVERAGEX evaluates [Total Sales] for each key. Define [Total Sales] as SUM of the line amounts, so no-sales customers produce BLANK and are excluded from the average. Include zeros explicitly only if the business definition requires them.
Avg Sales per Customer =
AVERAGEX ( VALUES ( DimCustomer[CustomerKey] ), [Total Sales] )Solution. The customer totals are €100 and €60, so the average is €80. The three order lines average €53.33.
Why the other is wrong. It answers a different question (average line value). The error comes from not matching the unit of analysis to the grain of the table.
Complex iterators over large tables can be expensive. Some simple expressions are optimized efficiently, so evaluate the query plan and timings. Iterate at the grain required by the calculation.
4. Table filtering
4.1 FILTER versus Boolean filters
Prefer a Boolean filter argument when the predicate meets the CALCULATE rules, such as a direct comparison of a column to a constant. Boolean predicates can refer to columns of one table, but cannot reference a measure directly. Use FILTER over the required keys when you need a per-key measure condition.
-- Efficient: one column predicate
High Value Sales = CALCULATE ( [Total Sales], FactSales[NetAmount] > 1000 )
-- Needed when the condition uses a measure
Big Customers Sales =
CALCULATE ( [Total Sales], FILTER ( VALUES ( DimCustomer[CustomerKey] ), [Total Sales] > 50000 ) )Do not write FILTER ( ALL ( FactSales ), ... ) over a fact table when a column predicate is enough. A broader table filter can change results and increase the work the engine does.
4.2 Removing and keeping filters
| Function | Effect |
|---|---|
ALL ( table or columns ) |
Removes all filters on the table or the columns |
ALLEXCEPT ( table, col1, ... ) |
Removes all filters on the table except those on the listed columns |
ALLSELECTED ( ... ) |
Removes the filters of the current visual but keeps the outer filters (slicers, page filters) |
REMOVEFILTERS ( ... ) |
Same as ALL when used as a CALCULATE modifier, clearer in intent |
KEEPFILTERS ( filter ) |
Intersects the new filter with the existing filter instead of replacing it |
VALUES ( col ) / DISTINCT ( col ) |
Currently visible values (VALUES can include a blank member) |
Example. "Percent of the visible total" in a matrix with a year slicer: DIVIDE ( [Total Sales], CALCULATE ( [Total Sales], ALLSELECTED ( DimProduct ) ) ). If the report also has a product slicer, ALL on DimProduct removes its product filters. The year filter from DimDate still applies. Compare the two denominators with both slicers active.
KEEPFILTERS preserves intersections with ordinary slicer and visual filters. It does not grant access to rows hidden by RLS. For example, CALCULATE ( [Total Sales], KEEPFILTERS ( DimProduct[Color] = "Red" ) ) returns blank if the user's current selection excludes Red, instead of overriding the selection.
4.3 CALCULATETABLE and table expressions
CALCULATETABLE is the table-returning sibling of CALCULATE. Use it with SUMMARIZECOLUMNS, ADDCOLUMNS and TOPN to build tables in a query (lesson 7) or in a calculated table.
EVALUATE
TOPN (
5,
SUMMARIZECOLUMNS ( DimProduct[ProductKey], DimProduct[ProductName], "Sales", [Total Sales] ),
[Sales], DESC,
DimProduct[ProductKey], ASC
)
ORDER BY [Sales] DESC, DimProduct[ProductKey] ASC5. Window functions
DAX window functions return rows relative to a position inside a partition of an ordered table, without writing complex time-intelligence or EARLIER logic. They work on any ordering, not only dates.
| Function | Returns |
|---|---|
INDEX ( position, relation, orderBy, ... ) |
The row at an absolute position (for example the first, last or third) |
OFFSET ( delta, relation, orderBy, ... ) |
The row a number of positions before or after the current row |
WINDOW ( from, fromType, to, toType, relation, orderBy, ... ) |
A range of rows (running totals, moving averages) |
RANK, ROWNUMBER |
The rank or sequential number of the current row |
Use a relation with one row per ordered position, such as a list of distinct YearMonthKey values from the date table. ORDERBY sets the sequence. PARTITIONBY restarts it for each group. MATCHBY can identify the current row when the ordering columns do not uniquely identify it.
For the following measures, the visual is grouped by the unique YearMonthKey. Restrict them to that level when subtotals have no meaningful current month.
Sales Previous Selected Month =
CALCULATE (
[Total Sales],
OFFSET ( -1, ALLSELECTED ( DimDate[YearMonthKey] ), ORDERBY ( DimDate[YearMonthKey], ASC ) )
)
Moving 3 Selected Month Sales =
CALCULATE (
[Total Sales],
WINDOW ( -2, REL, 0, REL, ALLSELECTED ( DimDate[YearMonthKey] ), ORDERBY ( DimDate[YearMonthKey], ASC ) )
)
Product Rank =
IF (
ISINSCOPE ( DimProduct[ProductDisplay] ),
RANK ( DENSE, ALLSELECTED ( DimProduct[ProductDisplay] ), ORDERBY ( [Total Sales], DESC ) )
)REL means relative positions. A frame from -2 to 0 includes the two previous positions and the current one, where available. ABS uses absolute positions in the partition. These functions operate over the supplied rows. If February is excluded, the row before March might be January. Use a complete calendar and calendar time intelligence for strict calendar-month comparisons. ProductDisplay in the rank example is a label unique per product.
Worked example: cumulative total across the selected months of each year
Use a visual with Year and a unique numeric YearMonthKey on its rows. The relation below contains one row per available month in the selection. PARTITIONBY resets the window for each year. At subtotals, the measure returns blank because the visual has no current month.
Selected Months Running Sales =
IF (
ISINSCOPE ( DimDate[YearMonthKey] ),
CALCULATE (
[Total Sales],
WINDOW (
1, ABS, 0, REL,
ALLSELECTED ( DimDate[Year], DimDate[YearMonthKey] ),
ORDERBY ( DimDate[YearMonthKey], ASC ),
DEFAULT,
PARTITIONBY ( DimDate[Year] )
)
)
)For a previous selected month comparison, use OFFSET with the same month ordering. Keep the year partition if the comparison should return blank at the first selected month of each year. To compare across years, include both years in the relation and omit that partition. This measure starts with the first selected month, which can be later than January. Use DATESYTD with an appropriate date table when the requirement is calendar year-to-date.
Exam tip. The study guide lists "window functions" explicitly. Know the roles of
INDEX,OFFSET,WINDOW,RANK,ROWNUMBER, and the parametersORDERBY,PARTITIONBY,REL/ABS.
6. Information functions
Information functions test the state of values or the filter context so a measure can adapt.
| Function | Use |
|---|---|
ISBLANK ( x ) |
Detect a blank result, often to avoid showing zeros |
ISFILTERED ( col ) |
True if the column is directly filtered |
ISCROSSFILTERED ( col ) |
True if the column is filtered directly or through a relationship |
HASONEVALUE ( col ) / SELECTEDVALUE ( col, alt ) |
One value in context, to read a slicer or detect a total row |
ISINSCOPE ( col ) |
True if the column is a level in the visual's current grouping (reliable for hierarchies) |
USERPRINCIPALNAME ( ) |
The signed-in user, used in dynamic row-level security |
CONTAINSSTRING, ISNUMBER, ISTEXT, ISERROR |
Value tests |
Detecting a total row correctly:
Margin % Display =
IF ( ISINSCOPE ( DimProduct[ProductName] ), [Margin %], BLANK () )This applies the report’s choice to suppress the percentage at higher levels. A properly calculated ratio can also be meaningful at a total. HASONEVALUE answers a different question and can be true at a total when a slicer leaves one product.
Dynamic row-level security example: a role with the filter DimUser[Email] = USERPRINCIPALNAME () on a security table related to the fact table.
7. Calculation groups
A calculation group is a table with one column (for example Time Calc) whose rows are calculation items. Each item is a DAX expression that modifies an explicit measure by using SELECTEDMEASURE (). One group with five items replaces dozens of measures such as "Sales YTD", "Margin YTD", "Cost YTD".
-- Calculation group: Time Calc
-- Item "Current"
SELECTEDMEASURE ()
-- Item "YTD"
CALCULATE ( SELECTEDMEASURE (), DATESYTD ( DimDate[Date] ) )
-- Item "Prior Year"
CALCULATE ( SELECTEDMEASURE (), SAMEPERIODLASTYEAR ( DimDate[Date] ) )
-- Item "YoY %"
VAR Current = SELECTEDMEASURE ()
VAR Prior = CALCULATE ( SELECTEDMEASURE (), SAMEPERIODLASTYEAR ( DimDate[Date] ) )
RETURN DIVIDE ( Current - Prior, Prior )Facts to know:
| Topic | Detail |
|---|---|
| Authoring | Power BI Desktop model view (Calculation group), Tabular Editor, or the web model editing experience |
| Prerequisite | Implicit measures must be disabled (Desktop does this when you create the first calculation group) |
| Precedence | When several groups apply, the precedence number decides the order; higher precedence is applied first |
| Format | Each item can have a format string expression |
| Direct Lake | Calculation groups are supported special objects in both flavors |
| Related functions | SELECTEDMEASURE, SELECTEDMEASURENAME, ISSELECTEDMEASURE |
Use ISSELECTEDMEASURE to branch for measures that need a different transformation. Whether a ratio should show YoY change is a business rule. For example, a margin percentage might need a percentage-point difference instead of relative growth.
Example. A manufacturer has 12 base measures and wants current, YTD, prior year and YoY %. Without a calculation group that is 48 measures; with one group of four items it is 12 measures and four items.
7.1 Pitfalls
- Calculation items apply to measures, not to columns used in a visual.
- Two groups touching the same dimension need an explicit precedence plan.
- Calculation groups make measures variant, which can affect an expression reused as a dynamic format string. If the format-string expression needs a text cast, apply it there. Keep the business-value measure numeric.
8. Dynamic format strings
A dynamic format string changes how a measure is displayed according to context, while the measure stays numeric. This is better than FORMAT (), which returns text and breaks charts and sorting.
-- Format string expression of the measure [Revenue]
SWITCH (
TRUE (),
SELECTEDVALUE ( DimCurrency[Code] ) = "EUR", "#,0.00 €",
SELECTEDVALUE ( DimCurrency[Code] ) = "USD", "$#,0.00",
"#,0.00"
)
The format-string expression returns text that describes the display. The measure still returns a number. Set the visual’s Display units deliberately so they do not override the format.
Dynamic format strings can be applied to one measure or to a calculation item, so that a "YoY %" item always shows a percentage while "Current" keeps the measure's format. When a calculation group and a measure both define a format, the calculation group item with the highest precedence wins.
Worked example: multi-currency display.
Statement. A model has one [Revenue] measure in a reporting currency. A slicer DimCurrency[Code] selects EUR, USD or JPY. The Revenue measure already converts the amount into that selected reporting currency. The display must match the currency, including no decimals for JPY. The visual must stay numeric so a column chart sorts correctly.
Reasoning.
- FORMAT returns text, which is unsuitable for chart values that require a numeric measure.
- Add a dynamic format string to
[Revenue]: aSWITCHonSELECTEDVALUE ( DimCurrency[Code] ). - Return a different format string per code, and a neutral default when several currencies are selected.
Solution. Use a format-string expression such as the following on Revenue. A format string changes display only. It does not perform exchange-rate conversion.
SWITCH (
SELECTEDVALUE ( DimCurrency[Code] ),
"EUR", "#,0.00 €",
"USD", "$#,0.00",
"JPY", "¥#,0",
"#,0.00"
)Why the others are worse. FORMAT breaks numeric behavior; a separate measure per currency multiplies the model's measures; changing the column format in the lakehouse is static.
9. Field parameters
A field parameter lets users switch fields or measures through a slicer. Create it with Modeling > New parameter > Fields so Power BI adds the parameter metadata. The following is the generated expression shape, assuming these measures live in the Sales table.
Metric Selector = {
( "Revenue", NAMEOF ( Sales[Revenue] ), 0 ),
( "Margin", NAMEOF ( Sales[Margin] ), 1 ),
( "Units", NAMEOF ( Sales[Units] ), 2 )
}The three columns are the display name, the field reference and the sort order. You create it in Power BI Desktop (Modeling > New parameter > Fields), then place the parameter column in a visual's axis or values and the display-name column in a slicer. Field parameters can contain columns or explicit measures. A plain live connection needs a local model before you can create a parameter. Editing the generated DAX table preserves its metadata. Creating an arbitrary table with the same rows alone does not configure a field parameter.
| Feature | Field parameter | Calculation group |
|---|---|---|
| Changes | Which field a visual shows | How a measure is calculated |
| Created from | Desktop field-parameter UI and its generated table metadata | Calculation items |
| Typical use | Let users pick metric or dimension | Time intelligence, currency, scenario |
| Direct Lake | Supported | Supported |
Common pitfalls
- Capturing a measure in a variable and then trying to change its filter context with
CALCULATE. - Using
FILTER ( ALL ( FactTable ), ... )where a Boolean column filter is enough. - Using
ALLwhereALLSELECTEDis needed, which makes percentages ignore slicers. - Averaging a column when the question is average per entity.
- Using
FORMATfor display and then wondering why a chart sorts as text. - Testing a total row with
HASONEVALUEwhereISINSCOPEis the reliable choice. - Applying one time calculation to every measure without checking whether ratios and balances need different semantics.
- Writing hundreds of near-identical time-intelligence measures instead of a calculation group.
Exam tip. The question describes a symptom (wrong share, text-sorted axis, 48 duplicate measures) and asks for the construct. Map: wrong denominators →
ALLvsALLSELECTED/variables; text-sorted display → dynamic format string; duplicated time measures → calculation group; user chooses metric → field parameter; previous row or running total → window function.
Mini case study
Context. Contoso Retail has a semantic model with [Revenue], [Cost], [Margin], [Margin %]. Requirements: (1) users must view each measure as current, year-to-date or year-over-year; (2) the YoY item must show a percentage; (3) executives want a visual where they can pick Revenue, Margin or Units; (4) the three highest store-revenue levels inside the selected region, including ties; (5) a total row that does not display margin percentage at category level.
Solution.
- A calculation group
Time Calcwith items Current, YTD, Prior Year and YoY %. - A dynamic format string on the YoY % item returning
"0.0%", so the measure stays numeric. - A field parameter
Metric Selectorwith the three measures, used in the visual values and a slicer. - Use a unique StoreDisplay label on the visual. Evaluate
RANK ( DENSE, ALLSELECTED ( DimStore[StoreDisplay] ), ORDERBY ( [Revenue], DESC ) )at the StoreDisplay level. Keep ranks 1–3 and exclude BLANK ranks. The region slicer remains in context. Dense ranking can return more than three stores when revenue ties. Margin % Display = IF ( ISINSCOPE ( DimProduct[ProductName] ), [Margin %] ).
Comment. Each requirement maps to one construct, and none requires duplicating measures. Adding the calculation group requires implicit measures to be off, which should be communicated to report authors.
Key terms
- Filter context / row context: sets of filters or the current row used when evaluating DAX.
- Context transition: conversion of a row context into filters by
CALCULATE. - Variable (
VAR): named value evaluated once. - Iterator: function evaluating an expression row by row (
SUMX,AVERAGEX). - Window function:
INDEX,OFFSET,WINDOW,RANK,ROWNUMBER. - Calculation group: table of calculation items modifying measures via
SELECTEDMEASURE. - Dynamic format string: DAX expression returning a format string for a measure or item.
- Field parameter: calculated table that switches fields or measures in visuals.
Summary checklist
- I can explain filter context, row context and context transition.
- I use variables for reuse and readability and know their frozen-context behavior.
- I choose between aggregators and iterators from the grain of the question.
- I can use
ALL,ALLSELECTED,KEEPFILTERS,FILTERandCALCULATETABLEcorrectly. - I can write
OFFSET,WINDOWandRANKmeasures withORDERBYandPARTITIONBY. - I can use
ISINSCOPE,SELECTEDVALUEandUSERPRINCIPALNAME. - I can build a calculation group with a dynamic format string and a field parameter.
Official sources
- Study guide for Exam DP-600: https://learn.microsoft.com/en-us/credentials/certifications/resources/study-guides/dp-600 (opens in a new tab)
- Create calculation groups in Power BI: https://learn.microsoft.com/en-us/power-bi/transform-model/calculation-groups (opens in a new tab)
- Create dynamic format strings for measures: https://learn.microsoft.com/en-us/power-bi/create-reports/desktop-dynamic-format-strings (opens in a new tab)
- DAX variables: https://learn.microsoft.com/en-us/dax/best-practices/dax-variables (opens in a new tab)
- DAX window relation design: https://learn.microsoft.com/en-us/dax/best-practices/dax-understand-orderby (opens in a new tab)
- Field parameters: https://learn.microsoft.com/en-us/power-bi/create-reports/power-bi-field-parameters (opens in a new tab)
- DAX reference: https://learn.microsoft.com/en-us/dax/ (opens in a new tab)
- Direct Lake overview: https://learn.microsoft.com/en-us/fabric/fundamentals/direct-lake-overview (opens in a new tab)
