Sub topic 9
Writing measures against the star
This chapter assumes you can load data into Power BI Desktop, read the Model view, and write simple DAX. It also assumes you have a star schema with one-to-many, single-direction relationships from dimensions to a fact table. The chapter shows how measures use that shape and which mistakes break them.
Measures versus columns
A measure is a DAX expression that is evaluated when a visual is drawn. It is not stored per row. A calculated column is evaluated once at refresh and stored in the model.
On a star schema, put numeric aggregations in measures on the fact table and keep descriptive attributes in dimensions. The measure then reacts to whatever the user filters, such as a slicer on Category or a row on a matrix.
Here are the two base measures used in this chapter:
Total Sales = SUM ( Sales[SalesAmount] )
Total Quantity = SUM ( Sales[Quantity] )Neither measure mentions a product, a date, or a customer. The filters come from outside the measure.
Where the filters come from
Every cell in a visual has a filter context. This is the set of filters that apply to that cell. It is built from:
- The fields on rows, columns, and axes of the visual.
- Slicers and report, page, and visual filters.
- Filters from other visuals when users cross-filter.
Dimension filters travel along relationships to the fact table. Suppose DimProduct[Category] is set to "Bikes". The filter passes across the one-to-many relationship to Sales and keeps only the Bikes rows. SUM then adds up the remaining rows.
This is why you rarely need FILTER or LOOKUPVALUE in a star schema. The relationships do the work.
Put the right columns on the axes
A measure only responds to dimension filters if the field in the visual comes from the dimension. If you drag Sales[ProductKey] onto an axis instead of DimProduct[ProductName], the visual still works. The visual would then show keys instead of names, and it would skip filters that exist only on the dimension.
Follow these rules:
- Use dimension columns for axes, slicers, and filters.
- Use fact columns only inside measures.
- Hide the fact table's key columns and any numeric column that is meant to be aggregated, so report authors see only the measures.
Explicit measures over implicit ones
Power BI can sum a numeric column automatically when you drag it into a visual. This is an implicit measure. Prefer explicit measures for these reasons:
- They can be reused in other measures.
- They have a fixed definition, so two report pages cannot disagree.
- They work in tools that do not auto-aggregate, such as Excel PivotTables over the model.
In the Model view, set the column's Summarize by property to None for numeric columns that should not be summed, such as a year number or a key.
Building measures on measures
Define a base measure once and build on it. This keeps definitions in one place.
Average Selling Price =
DIVIDE ( [Total Sales], [Total Quantity] )DIVIDE returns a blank when the denominator is zero or blank. A plain / would raise an error in that case. Use DIVIDE for ratios.
For ratios, do not average a per-row ratio column. Sum the numerator and the denominator, then divide. Averaging row-level ratios gives each row equal weight, which is wrong when rows have different quantities.
Changing the filter context with CALCULATE
CALCULATE evaluates an expression after changing the filter context. It is the main way to write measures such as "sales for Bikes only" or "sales for all products".
Bike Sales =
CALCULATE ( [Total Sales], DimProduct[Category] = "Bikes" )
Sales All Products =
CALCULATE ( [Total Sales], REMOVEFILTERS ( DimProduct ) )
Share of All Products =
DIVIDE ( [Total Sales], [Sales All Products] )Points to note:
- A filter argument such as
DimProduct[Category] = "Bikes"replaces any existing filter on that column. It does not add to it. REMOVEFILTERS ( DimProduct )clears every filter on the product dimension, but filters on the date and customer dimensions stay.- The filter is applied to the dimension, and then it flows to the fact table through the relationship.
If you filter a fact column directly, as in CALCULATE ( [Total Sales], Sales[Quantity] > 5 ), the filter applies at the row level of the fact table. That is valid, but it is a different question from a dimension filter.
Time intelligence on the date dimension
Time intelligence functions such as TOTALYTD, SAMEPERIODLASTYEAR, and DATEADD need a continuous date column. They work on the date dimension, not on a date column in the fact table.
Sales YTD =
TOTALYTD ( [Total Sales], 'Date'[Date] )
Sales Prior Year =
CALCULATE ( [Total Sales], SAMEPERIODLASTYEAR ( 'Date'[Date] ) )
Sales YoY % =
DIVIDE ( [Total Sales] - [Sales Prior Year], [Sales Prior Year] )The date table must contain every day in the range with no gaps, and it should be marked as a date table. The previous chapter's Date table does this.
Measures for a second date role
When Sales has an active relationship on order date and an inactive one on ship date, a measure can switch roles with USERELATIONSHIP:
Sales by Ship Date =
CALCULATE (
[Total Sales],
USERELATIONSHIP ( Sales[ShipDateKey], 'Date'[DateKey] )
)Inside this measure, the ship-date relationship is active and the order-date relationship is off. A date on the axis now means the ship date. Other measures in the same visual keep the order-date relationship. This lets you compare "ordered" and "shipped" on the same axis, as in this table:
| Month | Total Sales (order date) | Sales by Ship Date |
|---|---|---|
| Jan | 120,000 | 95,000 |
| Feb | 110,000 | 118,000 |
Both columns come from the same Date table. You do not need a second copy of it.
Common errors
The following problems show up often when you write measures over a star.
| Symptom | Likely cause | Fix |
|---|---|---|
| The same value repeats for every row of a visual | The axis field comes from a table with no relationship to the fact table | Create the relationship, or use a field from the connected dimension |
| Total is blank or too large for a dimension row | Fact rows have a key with no match in the dimension, which shows as a blank member | Fix the source keys or add an "Unknown" row to the dimension |
| A measure ignores a slicer | The measure uses `ALL` or `REMOVEFILTERS` on the slicer's table | Remove only the filters you intend to clear |
| Time intelligence returns wrong values | The date column comes from the fact table, or the date table has gaps | Use the marked date table's `Date` column |
| `USERELATIONSHIP` has no effect | The relationship does not exist, or the columns differ from the model | Check that the two columns match the inactive relationship exactly |
| A measure changes when a bidirectional filter is added | The extra filter path changes the filter context | Return to single-direction filters |
A useful debugging step is to put the dimension attribute and the base measure in a table visual. If the table looks right, the relationship and keys are fine, and the fault is in the measure's logic.
Measure design checklist
- Name measures clearly, with no table prefix, because they appear in the field list on their own.
- Store measures in the fact table, or in a dedicated measures table if the model has many.
- Set a format string for each measure, such as currency or a percentage.
- Build ratios from base measures and
DIVIDE. - Use variables (
VAR) to avoid repeating an expression and to make the logic easy to read.
Sales Growth vs Prior Year =
VAR Current = [Total Sales]
VAR Prior = [Sales Prior Year]
RETURN
IF ( NOT ISBLANK ( Prior ), DIVIDE ( Current - Prior, Prior ) )Exercise
Your model has Sales (fact) and DimProduct (dimension, related one-to-many). Write a measure that returns each product category's share of total sales, so that the share of all categories adds up to 100% when a category is on the rows of a matrix. Which function removes the filter, and why does the measure still respect a date slicer?
Show answer
Share of Sales = DIVIDE ( [Total Sales], CALCULATE ( [Total Sales], REMOVEFILTERS ( DimProduct ) ) ). REMOVEFILTERS ( DimProduct ) clears only the filters on the product dimension, which includes the category on the matrix row. A date slicer filters the Date dimension, so it is not cleared. The denominator is then total sales for the selected dates, and the shares add up to 100%.
Exercise
A visual shows one Total Sales value for each month, and the month comes from Sales[OrderDate]. A colleague says the YTD measure TOTALYTD ( [Total Sales], Sales[OrderDate] ) gives wrong values. What is the likely cause, and what is the fix?
Show answer
The fact table's date column usually has gaps and is not a marked date table, so time intelligence cannot rely on it. Use the continuous Date column of a dedicated date dimension that is marked as a date table, and relate it to the fact table through the date key: TOTALYTD ( [Total Sales], 'Date'[Date] ).