Chapter 14 – Power BI Semantic Modeling & DAX

📚 Chapter 14 – Power BI Semantic Modeling & DAX

1️⃣ The Power BI Semantic Model (VertiPaq Engine)

In modern Business Intelligence, Power BI replaces legacy SSAS Multidimensional Cubes and MDX with a Tabular Semantic Model powered by the VertiPaq in-memory columnar storage engine.

Import Mode vs. DirectQuery

  • Import Mode (Recommended): Loads a compressed snapshot of the relational warehouse tables (DWPubsSales) directly into system RAM. Delivers sub-second query performance and unlocks the full library of DAX functions.

  • DirectQuery: Leaves data in SQL Server and translates visual interactions into live T-SQL queries at runtime. Useful for massive real-time datasets, but restricts certain DAX transformations.

Data Ingestion Best Practices

When connecting Power BI Desktop to DWPubsSales (localhost), only import the base dimensional and fact tables:

  • Dimensions: DimAuthors, DimDates, DimPublishers, DimStores, DimTitles

  • Fact & Bridge Tables: FactSales, FactTitlesAuthors

  • Note: Do not import pre-flattened reporting views (such as vAllTables or vQuantitiesByTitleAndDate). Importing views alongside base star-schema tables causes data duplication in RAM and introduces ambiguous relationship paths.

2️⃣ Configuring Relationships & Filter Propagation

Cardinality and Cross-Filter Direction

  • Cardinality (1:*): One primary/surrogate key row in a dimension table filters many foreign key rows in a fact table (e.g., DimStores[StoreKey] $\rightarrow$ FactSales[StoreKey]).

  • Single Cross-Filter Direction: Filters flow downstream from the 1 side (Dimension) to the * side (Fact).

Handling Role-Playing Dimensions (Active vs. Inactive Paths)

Power BI strictly enforces one active filter path between any two tables to prevent ambiguous filter propagation.

  • In DWPubsSales, DimDates connects to two places:

    1. DimDates[DateKey] $\rightarrow$ FactSales[OrderDateKey] (Active — solid line)

    2. DimDates[DateKey] $\rightarrow$ DimTitles[PublishedDateKey] (Inactive — dotted line)

  • Because DimDates $\rightarrow$ FactSales and DimTitles $\rightarrow$ FactSales are both active, DimDates $\rightarrow$ DimTitles must remain Inactive. We activate it dynamically inside DAX formulas using USERELATIONSHIP().

Resolving Many-to-Many Bridge Tables (FactTitlesAuthors)

A single book title can be written by multiple authors, and an author can write multiple books:

  • DimAuthors[AuthorKey] $\rightarrow$ FactTitlesAuthors[AuthorKey] (1:*, Single)

  • DimTitles[TitleKey] $\rightarrow$ FactTitlesAuthors[TitleKey] (1:*, Both)

  • Setting the cross-filter direction between DimTitles and FactTitlesAuthors to Both allows an author selection to filter DimTitles, which in turn filters FactSales without double-counting sales quantities.

3️⃣ Calculated Columns vs. Measures

Understanding when to use a Calculated Column versus a Measure is the foundation of Power BI modeling:

Architectural Aspect Calculated Column Measure
Evaluation Context Row Context (evaluates row-by-row across a table). Filter Context (evaluates dynamically based on visuals, slicers, and matrix coordinates).
Evaluation Event Computed during Data Refresh. Computed on the fly at query time when a report visual renders.
Resource Cost Stored physically in RAM (increases .pbix file size). Uses CPU at runtime; consumes zero RAM.
Where to Use Slicers, chart axes, table row/column headers, static groupings. Aggregations, financial totals, ratios, percentages, and KPIs.

4️⃣ Core DAX Functions (SUM, SUMX, CALCULATE, FILTER, ALL)

4.1 Basic Aggregations & Row Iterators (SUM vs. SUMX)

  • SUM(): Aggregates a single numeric column within the active filter context:

    Total Sales Quantity = SUM(FactSales[SalesQuantity])
      
    
  • COUNTROWS(): Counts atomic transactions in a table:

    Number of Sales = COUNTROWS(FactSales)
      
    
  • SUMX() (Row-by-Row Iterator): Multiplying SUM(TitlePrice) * SUM(SalesQuantity) produces an order-of-operations error because it multiplies aggregated totals rather than individual line items. SUMX iterates over FactSales row by row, fetching the matching book price via RELATED(), multiplying first, and summing second:

    Total Revenue = 
    SUMX(
        FactSales,
        FactSales[SalesQuantity] * RELATED(DimTitles[TitlePrice])
    )
      
    

4.2 Modifying Filter Context (CALCULATE)

CALCULATE(<expression>, <filter1>, <filter2>, ...) is the most important function in DAX. It overrides, adds to, or removes filters from the visual before evaluating the expression:

  • Boolean Filter:

    Psychology Revenue = 
    CALCULATE(
        [Total Revenue],
        DimTitles[TitleType] = "Psychology"
    )
      
    
  • Activating an Inactive Relationship (USERELATIONSHIP):

    Revenue by Published Date = 
    CALCULATE(
        [Total Revenue],
        USERELATIONSHIP(DimDates[DateKey], DimTitles[PublishedDateKey])
    )
      
    

4.3 Table-Based Complex Filtering (FILTER)

Simple CALCULATE filters only accept Column = Constant predicates. When filtering by a measure or evaluating complex row expressions, wrap the target table in FILTER():

Bulk Order Revenue = 
CALCULATE(
    [Total Revenue],
    FILTER(
        FactSales,
        FactSales[SalesQuantity] >= 25
    )
)

4.4 Removing Filters for Ratios & Share of Total (ALL)

ALL() strips active filters from a specified table or column, allowing you to compute denominators for percentage-of-total KPIs:

All Publishers Revenue = 
CALCULATE(
    [Total Revenue],
    ALL(DimPublishers)
)

% of Publisher Revenue = 
DIVIDE([Total Revenue], [All Publishers Revenue], 0)

4.5 Conditional KPI Indicators (VAR, RETURN, SWITCH)

Using variables (VAR) improves readability and ensures the expression is evaluated once per cell:

Sales Qty KPI Status = 
VAR Qty = [Total Sales Quantity]
RETURN
SWITCH(
    TRUE(),
    ISBLANK(Qty) || Qty < 25, -1,
    Qty >= 25 && Qty <= 50, 0,
    1
)

5️⃣ Summary Reference: SSAS / MDX vs. Power BI / DAX

Concept Legacy SSAS Multidimensional (Ch. 11–13) Modern Power BI Semantic Model
Storage Engine MOLAP Disk Folders VertiPaq In-Memory Columnar Store
Query & Calculation Language MDX (Multidimensional Expressions) DAX (Data Analysis Expressions)
Atomic Row Calculation DSV Named Query (DerivedTotalPrice) SUMX() Iterator or Calculated Column
Role-Playing Dimensions Multiple Cube Dimension Instances Inactive Relationships + USERELATIONSHIP()
Many-to-Many Bridge Measure Group Intermediate Dimension Bidirectional Cross-Filtering (Both)

6️⃣ Hands-On Lab Exercise: Building the DWPubsSales Semantic Model & Report

Follow these steps in Power BI Desktop to build the semantic model from scratch and verify your DAX measures.

Step 1: Import the Warehouse Tables

  1. Open Power BI Desktop and click Home > Get data > SQL Server.
  2. Enter Server: localhost (or (local)), Database: DWPubsSales, and select Import mode. Click OK.
  3. In the Navigator, select only the 7 base tables:
    • DimAuthors, DimDates, DimPublishers, DimStores, DimTitles, FactSales, and FactTitlesAuthors.
    • (Leave vAllTables and vQuantitiesByTitleAndDate unchecked).
  4. Click Load.

Step 2: Configure Relationships in Model View

  1. Click the Model View icon (third icon on the far-left navigation bar) and arrange FactSales in the center.
  2. Verify that DimDates[DateKey] $\rightarrow$ FactSales[OrderDateKey], DimStores[StoreKey] $\rightarrow$ FactSales[StoreKey], DimTitles[TitleKey] $\rightarrow$ FactSales[TitleKey], and DimPublishers[PublisherKey] $\rightarrow$ DimTitles[PublisherKey] are all Active (1:*, Single cross-filter direction).
  3. Configure Role-Playing Dates:
    • Ensure DimDates[DateKey] $\rightarrow$ DimTitles[PublishedDateKey] is Inactive (dotted line). (If Power BI auto-activated it and deactivated DimTitles[TitleKey] $\rightarrow$ FactSales[TitleKey], deactivate the PublishedDateKey line first, then activate the TitleKey line).
  4. Configure the Many-to-Many Bridge:
    • Double-click the relationship line between DimTitles and FactTitlesAuthors.
    • Change Cross-filter direction from Single to Both and click Save.

Step 3: Create Calculated Columns (Row Context)

Switch to Report View (top icon on the left bar). In the Data pane on the right:

  1. Right-click DimTitles $\rightarrow$ New column, enter the formula below, and press Enter:
    PriceTier = 
    IF(
        DimTitles[TitlePrice] >= 20, 
        "Premium ($20+)", 
        IF(DimTitles[TitlePrice] >= 12, "Standard ($12-$19.99)", "Budget (<$12)")
    )
    
  2. Right-click FactSales $\rightarrow$ New column, enter the formula below, and press Enter:
    LineTotalPrice = 
    FactSales[SalesQuantity] * RELATED(DimTitles[TitlePrice])
    

Step 4: Create a Measures Container & Write Core DAX Measures

  1. On the Home ribbon, click Enter data, name the table _Measures, and click Load.
  2. In the Data pane, right-click _Measures $\rightarrow$ New measure and create your first measure:
    Total Sales Quantity = SUM(FactSales[SalesQuantity])
    
  3. Now expand _Measures, right-click Column1, and select Delete from model (or Hide). _Measures will convert into a dedicated Measure Group at the top of your Data pane.
  4. Right-click _Measures $\rightarrow$ New measure for each of the remaining measures:
    Number of Sales = COUNTROWS(FactSales)
    
    Total Revenue = 
    SUMX(
        FactSales,
        FactSales[SalesQuantity] * RELATED(DimTitles[TitlePrice])
    )
    
    Psychology Revenue = 
    CALCULATE(
        [Total Revenue],
        DimTitles[TitleType] = "Psychology"
    )
    
    Revenue by Published Date = 
    CALCULATE(
        [Total Revenue],
        USERELATIONSHIP(DimDates[DateKey], DimTitles[PublishedDateKey])
    )
    
    Bulk Order Revenue = 
    CALCULATE(
        [Total Revenue],
        FILTER(
            FactSales,
            FactSales[SalesQuantity] >= 25
        )
    )
    
    Top Performing Titles Revenue = 
    CALCULATE(
        [Total Revenue],
        FILTER(
            DimTitles,
            [Total Revenue] > 500
        )
    )
    
    All Publishers Revenue = 
    CALCULATE(
        [Total Revenue],
        ALL(DimPublishers)
    )
    
    % of Publisher Revenue = 
    DIVIDE([Total Revenue], [All Publishers Revenue], 0)
    

    (Select % of Publisher Revenue in the Data pane and click the % icon in the top Measure tools ribbon).

    Sales Qty KPI Status = 
    VAR Qty = [Total Sales Quantity]
    RETURN
    SWITCH(
        TRUE(),
        ISBLANK(Qty) || Qty < 25, -1,
        Qty >= 25 && Qty <= 50, 0,
        1
    )
    

Step 5: Build the Verification Report

On the Report View canvas, build these four visuals to test your semantic model:

  1. Top KPI Cards: Add four Card (123) visuals across the top of the canvas displaying Total Revenue, Total Sales Quantity, Number of Sales, and Bulk Order Revenue.
  2. Publisher & Category Matrix: Add a Matrix visual:
    • Rows: DimPublishers[PublisherName] and DimTitles[TitleType]
    • Values: Total Sales Quantity, Total Revenue, Bulk Order Revenue, and % of Publisher Revenue
    • Check: Verify % of Publisher Revenue totals 100.00% at the bottom.
  3. Order Date vs. Published Date Column Chart: Add a Clustered column chart:
    • X-axis: DimDates[Year]
    • Y-axis: Total Revenue and Revenue by Published Date
  4. Author Performance Table & Price Tier Slicer:
    • Add a Table visual with DimAuthors[AuthorName], Total Sales Quantity, Total Revenue, and Sales Qty KPI Status.
    • Add a Slicer visual with DimTitles[PriceTier].
    • Check: Click an author row in the table to verify that cross-filtering updates the KPI cards and Matrix via the FactTitlesAuthors bridge table. Save your file as DWPubsSales_SemanticModel.pbix.