Sub topic 3
Fact tables: events and numeric measurements
This chapter assumes you can load data into Power BI Desktop, read the Model view, and write simple DAX. You should also know what primary and foreign keys are. The previous chapter fixed the grain of the model. This chapter builds the fact table at that grain.
What a fact table stores
A fact table records things that happened. Each row is one event or one measurement at the chosen grain. Examples include an order line, a website click, a shipment, or a daily account balance.
A fact table has two kinds of columns:
- Foreign keys. These point to rows in dimension tables, such as
DateKeyandProductKey. - Numeric columns. These hold the values you add up or average, such as
QuantityandSalesAmount.
A fact table does not hold descriptive text like product names or customer cities. That text lives in dimension tables. Keeping the two apart is what lets one slicer on a dimension filter many facts.
Grain decides the rows
The grain states what one row means. For the sales model in this tutorial, it is "one row per order line". Every column in the table must be true for that grain. Quantity is the quantity on that line. SalesAmount is the amount on that line. An order-level value such as the shipping fee for the whole order does not fit, because repeating it on each line would inflate totals.
The grain also defines the table's natural key. Here, OrderNumber plus OrderLineNumber is unique. If you cannot name a combination of columns that is unique, the grain is probably unclear.
A fact table in SQL
This example creates a product dimension and a fact table at order-line grain.
CREATE TABLE DimProduct (
ProductKey INT PRIMARY KEY,
ProductName VARCHAR(100) NOT NULL,
Subcategory VARCHAR(50),
Category VARCHAR(50)
);
CREATE TABLE FactSales (
OrderNumber VARCHAR(20) NOT NULL,
OrderLineNumber INT NOT NULL,
DateKey INT NOT NULL,
ProductKey INT NOT NULL REFERENCES DimProduct (ProductKey),
Quantity INT NOT NULL,
SalesAmount DECIMAL(18, 2) NOT NULL,
PRIMARY KEY (OrderNumber, OrderLineNumber)
);Note what FactSales contains. OrderNumber and OrderLineNumber identify the line. DateKey and ProductKey connect to dimensions. Quantity and SalesAmount are the numbers. There is no product name, category, or month name.
In Power BI, you would import this table as Sales. The measures later in this chapter use that name.
Types of numeric columns
Not every number can be added the same way. This matters when you write measures.
| Kind | Meaning | Example | How to aggregate |
|---|---|---|---|
| Additive | Can be summed across all dimensions | `SalesAmount`, `Quantity` | `SUM` |
| Semi-additive | Can be summed across some dimensions but not time | Account balance, inventory on hand | Last value in the period, or average |
| Non-additive | Cannot be summed at all | Unit price, margin percentage, ratio | Recompute from additive parts |
Store the parts of a ratio, not the ratio itself. For margin percentage, keep SalesAmount and CostAmount in the fact table, and compute the percentage in a measure as total margin divided by total sales. Averaging a stored percentage column gives a wrong answer whenever rows have different weights.
Kinds of fact tables
Most fact tables are one of three kinds:
- Transaction facts. One row per event, such as an order line. This is the most common and the most flexible.
- Periodic snapshot facts. One row per entity per period, such as one row per account per month-end. These usually contain semi-additive values.
- Accumulating snapshot facts. One row per process instance, updated as it moves through stages. An order might have columns for order date, ship date, and delivery date. Each date is a foreign key to the date dimension, which leads to role-playing dimensions, covered in a later chapter.
Pick the kind that matches your grain, and do not mix kinds in one table. A daily balance and an individual transaction are different grains and belong in separate fact tables.
How measures use the fact table
A measure aggregates a fact column. Filters from dimension tables reach the fact table through relationships, so the measure does not need to know about them.
Total Sales = SUM ( Sales[SalesAmount] )
Total Quantity = SUM ( Sales[Quantity] )When a report visual groups by Product[Category], Power BI filters Sales to rows whose ProductKey belongs to each category, then evaluates SUM over those rows. Nothing in the measure mentions the category.
Prefer measures over numeric columns that users drag into visuals. A measure has a defined aggregation and a name, so every report that uses it gets the same result. A bare column makes each author choose a summarization, and Power BI may default to sum, average, or count.
Key columns in the fact table
Every foreign key in the fact table must match a key in its dimension. Two problems come up often.
- Orphan rows. A fact row has a key value with no matching dimension row. Power BI keeps the row but groups it under a blank member in visuals. Totals stay correct, but the blank category confuses readers. Fix this at the source or in Power Query, for example by adding an "Unknown" row to the dimension with a key such as
-1and mapping missing keys to it. - Wrong data type. Joining a text key to a whole-number key fails or forces conversions. Keep key columns as whole numbers where you can. They compress well and compare quickly.
Because OrderNumber and OrderLineNumber identify the row but are not used to relate to any dimension, you often do not need to load them into the model. Keep them only if users need to drill to the line or you need a distinct count of orders. A text column with one unique value per row is costly in memory and adds little.
Choosing what to keep in the fact table
A useful test for each candidate column is: is it a key, a number to aggregate, or a description?
- If it is a key to a dimension, keep it.
- If it is a number you aggregate, keep it.
- If it is descriptive text or a category, move it to a dimension.
- If it is a value that is constant per order, per customer, or per product, it belongs to a different grain. Move it to a dimension or to a separate fact table.
Edge cases follow from this test:
- Degenerate dimensions. An identifier such as
OrderNumberhas no attributes of its own. Leave it in the fact table instead of creating a one-column dimension. - Flags and codes. A status like "Shipped" or "Returned" has few distinct values. Put it in a small dimension rather than repeating text on millions of rows.
- Facts with no numbers. Some events carry no measure, such as a customer sign-up. The row itself is the fact, and you count rows with
COUNTROWS.
Exercise
A table has one row per order line with columns OrderNumber, OrderLineNumber, ProductKey, DateKey, Quantity, SalesAmount, ShippingFeeForOrder, and UnitMarginPercent. Which columns would you change or move, and why?
Show answer
ShippingFeeForOrder is order-level, so it does not match the order-line grain. Summing it across lines would count the fee once per line. Move it to an order-grain fact table, or allocate it across lines at the source. UnitMarginPercent is non-additive. Replace it with a cost column such as CostAmount and compute margin percentage in a measure as (total sales minus total cost) divided by total sales. The other columns are valid keys or additive numbers.
Exercise
A fact table has a ProductKey value of 9999 that does not exist in DimProduct. What does a visual grouped by Category show for those rows, and how can you fix it?
Show answer
The rows appear under a blank category. Totals remain correct, but the blank member is confusing. Fix it by adding an Unknown row to DimProduct and mapping unmatched keys to it, or by correcting the key at the source.