Practical Application of TREATAS Function in DAX

by | Power BI

Understanding the Dataset Requirements in DAX

Introduction

This section will walk you through steps to understand dataset requirements relevant for using the TREATAS function in DAX (Data Analysis Expressions).

Load Tables

Ensure your data is properly loaded within your model.

TableA = 
ADDCOLUMNS(
    Table1,
    "Category", Table1[Category]
)

TableB = 
ADDCOLUMNS(
    Table2,
    "Category", Table2[Category]
)

Check Column Names and Data Types

Verify column names and data types to avoid errors with TREATAS.

-- Display column data types
EVALUATE 
DATATABLE (
    "Column Name", STRING,
    "Data Type", STRING,
    {
        {"Category", "STRING"},
        {"Value", "INTEGER"}
    }
)

Ensure Relationships

Make sure relationships between tables are clear.

-- Visualize Relationships
-- Note: This is typically done within the data model UI in Power BI or SSAS

Using TREATAS Function

Syntax of TREATAS

Understand the proper syntax for using TREATAS:

TREATAS(<column>, <target_table>[<target_column>])

Example Implementation

Create a measure to filter TableA based on categories present in TableB.

FilteredMeasure = 
CALCULATE (
    SUM(TableA[Value]),
    TREATAS (
        VALUES(TableB[Category]),
        TableA[Category]
    )
)

Validate Results

Check if the measure returns correct results.

EVALUATE 
SUMMARIZECOLUMNS (
    TableA[Category],
    "Filtered Value", [FilteredMeasure]
)

Conclusion

To effectively use TREATAS:

  • Ensure tables are loaded and columns are correctly named and typed.
  • Confirm the relationships between tables.
  • Apply the TREATAS function correctly in your DAX measures.

Next Steps

Move on to the next unit of your curriculum after validating the above steps in your real-life project.

Practical Implementation of Setting Up the Data Model in DAX

1. Define the Tables for Data Model

-- Declare tables using DAX
VAR Customers = 
    ADDCOLUMNS(
        DATATABLE(
            "CustomerID", INTEGER,
            "CustomerName", STRING,
            {
                {1, "John Doe"},
                {2, "Jane Smith"}
            }
        ),
        "CustomerKey", [CustomerID]
    )

VAR Orders = 
    ADDCOLUMNS(
        DATATABLE(
            "OrderID", INTEGER,
            "CustomerID", INTEGER,
            "OrderDate", DATE,
            "OrderAmount", CURRENCY,
            {
                {101, 1, "2023-01-01", 100.00},
                {102, 2, "2023-02-15", 150.00}
            }
        ),
        "OrderKey", [OrderID]
    )

2. Establish Relationships

-- Create relationships between tables
CREATE_RELATIONSHIP(
    Orders[CustomerID],
    Customers[CustomerID]
)

3. Use TREATAS to Manipulate and Analyze Data

-- Summarize order amounts by treating Customers[CustomerID] as Orders[CustomerID]
VAR TREATASResult =
    SUMMARIZECOLUMNS(
        'Customers'[CustomerID],
        TREATAS(
            VALUES(Customers[CustomerID]),
            Orders[CustomerID]
        ),
        "TotalOrderAmount", SUM(Orders[OrderAmount])
    )

RETURN TREATASResult

This DAX implementation sets up the data model by defining tables, establishing relationships, and using the TREATAS function to manipulate and analyze the data.

Utilizing TREATAS to Filter Data

The task involves using the TREATAS function in DAX to filter data according to specific conditions. Below is the practical implementation which you can use directly in your DAX expressions.

Step 1: Define the Measure using TREATAS

Here’s a measure that filters sales data based on a predefined set of product categories:

FilteredSalesMeasure = 
CALCULATE (
    SUM ( Sales[Amount] ),
    TREATAS (
        { "Electronics", "Clothing" }, 
        Products[Category]
    )
)

Step 2: Applying the Measure in a Report

You can use this measure directly in your Power BI report to visualize the filtered sales data. For example, you might add it to a card visual or use it in a table to show sales amounts filtered by the specified categories.

Example Usage in a Context

If you have a table visual and you want to apply the FilteredSalesMeasure to show only relevant sales:

SalesByRegionFiltered = 
SUMMARIZE (
    Sales,
    Sales[Region],
    "Filtered Sales", 
    [FilteredSalesMeasure]
)

This will generate a summary table showing sales by region but filtered according to the categories specified in the TREATAS function.

Step 3: Adjusting Filter Conditions

You can adjust the filtering conditions by changing the values within the TREATAS function. For example, if you want to filter for different categories, simply modify the set of values:

FilteredSalesMeasure = 
CALCULATE (
    SUM ( Sales[Amount] ),
    TREATAS (
        { "Furniture", "Office Supplies" }, 
        Products[Category]
    )
)

Final Measure for Practical Usage

Here’s a final, ready-to-use measure example:

FilteredSales =
CALCULATE (
    SUM ( Sales[Amount] ),
    TREATAS (
        { "Electronics", "Furniture" }, 
        Products[Category]
    )
)

TotalFilteredSalesByRegion =
SUMMARIZE (
    Sales,
    Sales[Region],
    "Total Filtered Sales",
    [FilteredSales]
)

Now you can utilize this in your Power BI Report to get the filtered sales data by region based on the defined categories.

By following these steps, you can practically implement data filtering using the TREATAS function in DAX directly in your data model and reports.

#4 Part of the Project: Creating and Validating DAX Measures

Implementing DAX Measures

Measure 1: Total Sales

Total Sales = SUM(Sales[Amount])

Measure 2: Average Sales Price

Avg Sales Price = AVERAGE(Sales[Price])

Measure 3: Sales Amount by Region using TREATAS

Sales Amount by Region = 
CALCULATE(
    [Total Sales],
    TREATAS(
        VALUES(Regions[RegionName]), 
        Sales[Region]
    )
)

Measure 4: Total Units Sold

Total Units Sold = SUM(Sales[Quantity])

Validating DAX Measures

Validation Matrix

EVALUATE 
SUMMARIZECOLUMNS(
    Regions[RegionName],
    "Total Sales", [Total Sales],
    "Avg Sales Price", [Avg Sales Price],
    "Sales Amount by Region", [Sales Amount by Region],
    "Total Units Sold", [Total Units Sold]
)

Validation Steps in Power BI/Excel

  1. Verify that values accurately reflect changes in datasets.
  2. Ensure calculations are logical by inspecting derived results.
  3. Cross-check totals against manually calculated summaries.
  4. Check for correct filtering based on Regions and Sales.

Sample Query for Validation

EVALUATE 
SUMMARIZECOLUMNS(
    Sales[Region],
    "Filtered Total Sales", [Sales Amount by Region]
)

By running this validation query, you check if the measure [Sales Amount by Region] correctly filters and computes the sales amount based on the region context provided by TREATAS.

Building Interactive Reports and Dashboards Using DAX and TREATAS

Step 1: Define DAX Measures with TREATAS

Sales by Region

SalesByRegion = 
CALCULATE(
    SUM(Sales[SalesAmount]),
    TREATAS(
        VALUES(Geography[Region]),
        Sales[Region]
    )
)

Customer Count by Product

CustomerCountByProduct = 
CALCULATE(
    DISTINCTCOUNT(Customers[CustomerID]),
    TREATAS(
        VALUES(Products[ProductID]),
        Sales[ProductID]
    )
)

Step 2: Create Interactive Visual Elements in Power BI

Bar Chart: Sales by Region

  1. Create a bar chart.
  2. Drag the Region field from the Geography table to the Axis.
  3. Drag the SalesByRegion measure to the Values.

Pie Chart: Customer Distribution by Product

  1. Create a pie chart.
  2. Drag the ProductName field from the Products table to the Legend.
  3. Drag the CustomerCountByProduct measure to the Values.

Step 3: Add Visual Level Filters

Filter Sales by Region (Bar Chart)

  1. Select the bar chart.
  2. Drag the Region field to the Visual level filters.
  3. Apply any desired filter.

Filter Customer Distribution by Specific Product Category

  1. Select the pie chart.
  2. Drag the ProductCategory field to the Visual level filters.
  3. Apply any desired filter.

Step 4: Create Interactive Slicers

Region Slicer

  1. Create a slicer visual.
  2. Drag the Region field from the Geography table to the slicer.

Product Category Slicer

  1. Create another slicer visual.
  2. Drag the ProductCategory field from the Products table to the slicer.

Step 5: Sync Slicers Across Reports

  1. Select a slicer visual.
  2. Go to the View tab and select Sync slicers.
  3. Enable slicer synchronization across relevant report pages.

Step 6: Save and Share the Report

  1. Save the Power BI report file.
  2. Publish the report to the Power BI service.
  3. Share the dashboard link with relevant stakeholders.

Related Posts

Comprehensive Data Analysis using Power BI and DAX

Data Model Discovery Library

An interactive web-based application to explore and understand various data model examples across multiple industries and business functions.