Data Visualization with Power BI & Tableau

Chapter 6
Calculations with DAX and Tableau

Bachelors Program in Business Analytics
Data Visualization with Power BI & Tableau   •   Bachelor

Calculations with DAX and Tableau

Introduction

Data visualization is not only the presentation of existing numbers. In professional analytics, analysts must define business logic, transform row-level data into meaningful measures, compare performance across time, and ensure that calculations respond correctly to user selections. Power BI and Tableau both provide calculation languages, but they use different analytical models.

Power BI primarily uses Data Analysis Expressions (DAX), a formula language designed for tabular models. DAX distinguishes strongly between calculated columns, which are evaluated row by row during data refresh, and measures, which are evaluated dynamically in a filter context. Tableau uses calculated fields, parameters, sets, level-of-detail (LOD) expressions, and table calculations. Tableau calculations may operate at the data-source level, at a specified granularity, or across the visible marks in a view.

The distinction between stored row-level results and dynamically evaluated aggregations is central to designing reliable dashboards. A calculation can be syntactically valid but analytically wrong if it uses an inappropriate grain, ignores filter context, or mixes incompatible levels of detail.

Learning Objectives

By the end of this chapter, students should be able to:

  1. Explain row context, filter context, granularity, and aggregation.
  2. Create and evaluate DAX calculated columns and measures.
  3. Use DAX filter manipulation and time-intelligence functions appropriately.
  4. Create Tableau calculated fields, parameters, sets, LOD expressions, and table calculations.
  5. Select an appropriate calculation type for a business question.
  6. Build reusable metrics and validate them against business definitions.
  7. Identify performance, governance, and interpretation risks in analytical calculations.

1. The Analytical Grain and Context

The grain of a dataset is the level represented by one row. A sales table might contain one row per order line, while a customer table contains one row per customer. If an order-line table contains quantity and unit price, line revenue is calculated as:

Revenuei = Quantityi × UnitPricei

Here, i identifies a row, quantity is measured in units, unit price is measured in currency per unit, and revenue is measured in currency. The formula assumes that discounts, taxes, returns, and currency conversion are either absent or handled separately.

Total revenue is the sum of row revenues:

Total Revenue = ∑ Revenuei

A common error is to calculate total revenue as total quantity multiplied by average unit price. This may not equal the sum of line revenues when prices differ across products or transactions. Aggregation must therefore respect the meaning and grain of the measure.

Two kinds of context are especially important:

  • Row context: the current row being evaluated. It is natural in a calculated column and in certain iterator functions.
  • Filter context: the set of rows permitted by filters, slicers, relationships, visual dimensions, or calculation logic. It is fundamental to DAX measures.

For a filtered revenue measure, if F is the set of rows remaining after filters:

Revenue(F) = ∑i ∈ F Revenuei

The result changes when a user selects a year, region, product, or customer segment. A well-designed measure is therefore a function of context rather than a permanently stored number.

2. Choosing the Correct Calculation Type

The following decision framework is useful:

RequirementPower BI choiceTableau choice
Store a row-level result for every recordCalculated columnRow-level calculated field or data-source calculation
Respond dynamically to filtersMeasureAggregated calculated field
Allow a user to choose a value or metricDisconnected-table measure logic or field parameterParameter
Group members according to a ruleDimension or calculated columnSet
Calculate at a fixed or independent grainMeasure with context controlLOD expression
Compare visible marks or calculate running totalsMeasure, often with time logicTable calculation

A calculated column consumes model storage and is evaluated when data is refreshed. A measure is evaluated when a visual queries the model, so it normally provides greater flexibility and avoids storing repeated results. However, a measure cannot always replace a column: categorical grouping, relationships, sorting, and row-level filtering may require a physical column.

3. DAX Foundations

DAX expressions refer to tables and columns, and measures can be reused throughout a report. Typical aggregation functions include SUM, AVERAGE, MIN, MAX, and COUNTROWS. A basic measure is:

Total Sales = SUM(Sales[SalesAmount])

The expression sums the SalesAmount column in the current filter context. If the visual is grouped by region, the measure is evaluated separately for each region.

3.1 Calculated Columns

A calculated column is evaluated for each row. For example:

Line Revenue = Sales[Quantity] * Sales[Unit Price]

A margin column might be:

Line Margin = Sales[Sales Amount] - Sales[Cost Amount]

These expressions use row context implicitly. They are appropriate when the result is genuinely a property of each row and must be used as a category, relationship key, or input to later aggregation.

A percentage should generally not be stored as a row-level average if the required business measure is a ratio of totals. The correct gross-margin percentage is:

Gross Margin % = (Total Sales − Total Cost) ÷ Total Sales

provided total sales is nonzero. This is not necessarily equal to the average of row-level margin percentages because transactions may have different sales values.

3.2 Measures and Filter Context

A reusable DAX measure can be defined as:

Total Sales = SUM(Sales[Sales Amount])
Total Cost = SUM(Sales[Cost Amount])
Gross Margin = [Total Sales] - [Total Cost]
Gross Margin % = DIVIDE([Gross Margin], [Total Sales], 0)

DIVIDE is preferable to the division operator when a denominator may be zero or blank. The third argument specifies the alternate result; selecting zero is a business decision and should not conceal missing data in contexts where blank is more appropriate.

If a report is filtered to one region, both Total Sales and Total Cost respond to that filter. Thus the margin percentage remains a ratio of filtered totals.

3.3 Iterators and Context Transition

Iterator functions such as SUMX, AVERAGEX, and FILTER evaluate an expression over a table. For example:

Total Revenue = SUMX(Sales, Sales[Quantity] * Sales[Unit Price])

This is useful when revenue is not stored in a column or when the expression must be evaluated before aggregation. SUMX creates row context over the Sales table and sums the resulting values.

CALCULATE is one of the most important DAX functions. It evaluates an expression after modifying filter context:

Online Sales =
CALCULATE([Total Sales], Sales[Channel] = "Online")

A key advanced behavior is context transition: when CALCULATE is evaluated in row context, it can convert that row context into filter context. This explains why measures and calculated columns may behave differently and why careless use of CALCULATE can produce unexpected results.

3.4 Filter Modification

Suppose a report shows sales by product category, but management wants each category compared with all-category sales. A measure may remove a category filter:

All Category Sales =
CALCULATE([Total Sales], REMOVEFILTERS(Product[Category]))

A category share can then be expressed as:

Category Share = DIVIDE([Total Sales], [All Category Sales])

The numerator retains the current category context, while the denominator removes the category filter. The measure should be tested carefully when other filters, such as year or region, must remain active.

ALL, REMOVEFILTERS, ALLEXCEPT, and KEEPFILTERS have related but distinct purposes. The design question is not simply which function runs, but which filters should remain, be replaced, or be removed.

4. DAX Time Intelligence

Time intelligence requires a reliable date table. A proper date table normally contains one row per date, a continuous date range, and attributes such as year, quarter, month number, and month name. It should be marked as a date table and related to the relevant fact-table date.

Year-to-date sales are commonly written as:

Sales YTD = TOTALYTD([Total Sales], 'Date'[Date])

Previous-year sales may be written as:

Sales PY = CALCULATE([Total Sales], SAMEPERIODLASTYEAR('Date'[Date]))

Year-over-year change is:

YoY Change = Current Period Sales − Prior-Year Sales

and percentage change is:

YoY % = (Current Period Sales − Prior-Year Sales) ÷ Prior-Year Sales

The percentage is defined only when prior-year sales is nonzero and comparable. A measure such as DIVIDE([Total Sales] - [Sales PY], [Sales PY]) handles the arithmetic, but the analyst must still consider incomplete periods, newly opened stores, fiscal calendars, and missing dates.

5. Tableau Calculations

Tableau calculated fields use expressions such as:

SUM([Sales])
SUM([Profit])
SUM([Profit]) / SUM([Sales])

The final expression is a ratio of aggregates and is generally preferable to AVG([Profit] / [Sales]) when the business definition is total profit divided by total sales.

Tableau distinguishes aggregation from disaggregation. A field used in a view may be evaluated at the level of detail defined by dimensions in the view. Mixing aggregated and nonaggregated terms improperly can cause errors or misleading results. For example, a condition should generally compare aggregated values with aggregated values:

IF SUM([Sales]) > 100000 THEN "High" ELSE "Standard" END

5.1 Parameters

A parameter is a user-controlled value that can be used in calculations, filters, reference lines, or titles. A parameter called Top N can control a threshold, while a metric parameter can allow users to switch between Sales, Profit, and Quantity.

A conceptual metric-switching calculation might be:

CASE [Metric Parameter]
WHEN "Sales" THEN SUM([Sales])
WHEN "Profit" THEN SUM([Profit])
WHEN "Quantity" THEN SUM([Quantity])
END

Parameters do not automatically filter a data source. They provide a value to calculations; the calculation determines its effect. This distinction is important when explaining dashboard behavior to users.

5.2 Sets

A set is a defined subset of dimension members. A set may be fixed, condition-based, top-N, or dynamically selected by the user. Sets can support questions such as “How do selected strategic accounts compare with all other accounts?” A calculated field can classify marks as members and non-members of a set, enabling segmentation and comparison.

Sets are useful for cohort analysis, competitor groups, priority products, and user-selected comparisons. Their validity depends on a clearly documented membership rule and refresh behavior.

5.3 Level-of-Detail Expressions

LOD expressions allow Tableau to specify the granularity at which a calculation is performed, independently of some or all dimensions in the view.

  • FIXED computes at explicitly named dimensions.
  • INCLUDE adds dimensions to the view’s level of detail.
  • EXCLUDE removes dimensions from the view’s level of detail.

For example:

{ FIXED [Customer ID] : SUM([Sales]) }

calculates each customer’s total sales, even when the view is displayed by region or product category. Average customer sales can then be calculated from the customer-level result, subject to the desired aggregation and filter behavior.

LOD expressions require careful attention to filters. In general, context filters are applied before a FIXED LOD, whereas ordinary dimension filters may be applied later depending on the workbook structure. Analysts should test this behavior rather than relying on assumptions.

5.4 Table Calculations

Table calculations operate on the results already returned to the visualization. They are therefore dependent on the layout and addressing of the view. Common examples include running totals, moving averages, rank, percent of total, and differences from a prior period.

A running total for monthly sales is conceptually:

Running Totalt = ∑k=1t Salesk

where months are ordered chronologically and t is the current month. If the table calculation is addressed incorrectly, the running total may restart by category, run across columns instead of rows, or use an unintended ordering.

A three-month moving average is:

Moving Averaget = (Salest + Salest−1 + Salest−2) ÷ 3

This formula assumes that all three periods exist and are comparable. At the beginning of a series, Tableau may use fewer periods or return a null depending on the configuration. The analyst must state which convention is being used.

6. Worked Comparison: Customer Profitability

Assume the following simplified data:

CustomerSalesCostRegion
A10,0006,000East
B4,0003,000East
C6,0002,000West

Total sales are 20,000 and total cost is 11,000. Therefore:

Gross Margin = 20,000 − 11,000 = 9,000
Gross Margin % = 9,000 ÷ 20,000 = 0.45 = 45%

If the analyst averages customer margin percentages, the result is:

  • Customer A: 40%
  • Customer B: 25%
  • Customer C: 66.67%
  • Unweighted average: approximately 43.89%

The unweighted average differs from the overall margin of 45% because customers have different sales amounts. If the business question is “What percentage of sales becomes margin?”, 45% is the correct measure. If the question is “What is the average customer margin rate?”, an explicitly defined customer-level average may be appropriate.

In Power BI, the preferred reusable measures are:

Total Sales = SUM(Sales[Sales])
Total Cost = SUM(Sales[Cost])
Margin % = DIVIDE([Total Sales] - [Total Cost], [Total Sales])

In Tableau, the equivalent aggregate calculation is:

(SUM([Sales]) - SUM([Cost])) / SUM([Sales])

A customer-level LOD expression can be used when the view requires each customer’s total independent of the displayed dimensions:

{ FIXED [Customer] : SUM([Sales]) }

The calculation type depends on whether the objective is an overall ratio, a customer-level attribute, or a visual comparison across displayed marks.

7. Illustrative Case: Retail Performance Dashboard

Background

This illustrative case concerns Northstar Retail, a fictional chain with stores, online transactions, products, customers, and daily sales. Senior managers want a dashboard showing revenue, gross margin, year-over-year growth, product concentration, and performance of strategic customers.

Problem

The first dashboard averaged transaction-level margin percentages, treated missing months as zero, and used a visual running total that restarted unexpectedly for each product. Managers therefore received inconsistent profitability and trend information.

Analysis

The analytics team documented the grain of each table and defined the business metrics. Revenue was defined as the sum of line revenue after discounts. Gross margin was defined as revenue minus product cost. Margin percentage was defined as total margin divided by total revenue, not as an average of row-level percentages. A continuous date table was added, and incomplete current months were flagged rather than silently compared with complete prior months.

Approach and Solution

In Power BI, the team created measures for total sales, total cost, margin, margin percentage, prior-year sales, and year-to-date sales. CALCULATE was used to control comparison denominators, while the date table supported time intelligence. Columns were reserved for row-level classifications such as channel group and product band.

In Tableau, a parameter allowed users to select Sales, Margin, or Quantity. A set identified strategic customers. A FIXED LOD expression calculated customer sales independently of the visual layout. A table calculation produced a running total only after the team configured the correct addressing and chronological sort.

Outcome

The revised dashboard produced consistent metrics across pages. Managers could distinguish current-period performance from year-to-date performance, compare selected customers with the remainder of the customer base, and identify whether margin changes were caused by price, product mix, or cost.

Learning Points

  1. Metric definitions must precede formula writing.
  2. The data grain determines which aggregations are valid.
  3. Dynamic measures are preferable for filter-responsive KPIs.
  4. LOD and context controls must be tested with realistic filters.
  5. A visually plausible calculation can still be conceptually wrong.

8. Validation, Performance, and Governance

Calculation development should follow a validation cycle:

  1. State the business definition in plain language.
  2. Identify the source grain and relevant relationships.
  3. Build the simplest calculation that represents the definition.
  4. Test totals against an independent source such as a ledger or SQL query.
  5. Test filters, nulls, zero denominators, duplicate records, and incomplete periods.
  6. Compare results at multiple grains: overall, monthly, regional, and transaction level.
  7. Document assumptions, refresh timing, ownership, and known limitations.

Performance depends on model design as well as formula complexity. In Power BI, a star schema, integer keys, a dedicated date table, and measures rather than unnecessary calculated columns often improve maintainability and query performance. In Tableau, extracts, appropriate data-source design, reducing unnecessary high-cardinality dimensions, and limiting expensive calculations can improve responsiveness.

Governance requires a certified definition of important metrics. “Revenue,” “active customer,” and “on-time delivery” should have named owners, documented inclusion rules, and version-controlled changes. Security is also relevant: row-level security in Power BI and user filters or data policies in Tableau must be tested so that calculations do not expose restricted aggregates or reveal sensitive information through indirect comparisons.

Ethically, analysts should not use parameters or visual design to encourage a preferred conclusion while hiding unfavorable periods or populations. Suppression, rounding, and treatment of missing values should be disclosed when they could affect decisions. AI-assisted formula generation can accelerate development, but generated expressions require human review for context behavior, privacy, bias, and business validity.

9. Best-Practice Checklist

  • Define the metric before selecting the calculation feature.
  • Confirm the grain of every source table.
  • Use measures for dynamic KPIs and columns for stable row attributes.
  • Prefer ratios of sums when the business definition is a ratio of totals.
  • Use a complete, validated date table for time intelligence.
  • Protect divisions with explicit zero and blank handling.
  • Document filter-removal behavior in denominators.
  • Use Tableau LOD expressions when the required grain differs from the view.
  • Configure table-calculation addressing and sorting explicitly.
  • Validate results against independent totals and edge cases.
  • Minimize duplicated business logic across reports.
  • Apply access controls and disclose material assumptions.

Chapter Summary

DAX and Tableau provide complementary mechanisms for turning data into reusable analytical metrics. DAX calculated columns operate in row context and are stored after refresh, whereas DAX measures are evaluated dynamically in filter context. CALCULATE, iterators, filter modification, and time-intelligence functions make DAX powerful but require careful reasoning about context and relationships.

Tableau calculated fields express row-level and aggregate logic; parameters provide user-controlled inputs; sets define member groups; LOD expressions control calculation grain; and table calculations operate on the marks returned to a view. Across both platforms, correct aggregation depends on grain, metric definitions, denominator choices, date completeness, and filter behavior. Reliable dashboards require not only correct syntax but also validation, documentation, governance, performance awareness, and ethical communication.

Key Terms

Calculated column: A stored row-level expression evaluated during refresh.

Measure: A dynamic aggregation evaluated in the current query or filter context.

Row context: The current record being evaluated.

Filter context: The set of rows allowed by filters and relationships.

Granularity: The level of detail represented by a record or calculation.

Iterator: A function that evaluates an expression for each row of a table.

Context transition: Conversion of row context into filter context, commonly through CALCULATE.

Time intelligence: Calculations involving periods, such as year-to-date or prior-year values.

Calculated field: A Tableau expression created from fields, constants, functions, and logic.

Parameter: A user-controlled value supplied to a Tableau calculation or control.

Set: A subset of dimension members defined by selection or a rule.

LOD expression: A Tableau expression that specifies calculation granularity.

FIXED LOD: An LOD expression calculated at explicitly named dimensions.

Table calculation: A calculation performed on values already present in a Tableau view.

Aggregation: Combining multiple values using operations such as sum or average.

Star schema: A model with a central fact table connected to descriptive dimension tables.

Filter manipulation: Deliberately preserving, replacing, or removing filters in a calculation.

Metric governance: The documentation, ownership, validation, and control of business measures.

Review Questions

Short Answer Questions

  1. What is the difference between row context and filter context in DAX?
  2. Why is a ratio of totals often preferable to an average of row-level ratios?
  3. What purpose does a Tableau parameter serve?
  4. Distinguish a Tableau LOD expression from a table calculation.
  5. Why is a continuous date table important for time intelligence?

Long Answer Questions

  1. Compare calculated columns and measures in Power BI, including appropriate use cases and trade-offs.
  2. Explain how CALCULATE changes the interpretation of a DAX expression.
  3. Discuss the role of grain in designing revenue and profitability metrics.
  4. Explain the differences among Tableau parameters, sets, and LOD expressions.
  5. Design a validation and governance process for an executive KPI dashboard.

Analytical / Application Questions

  1. A company reports an average transaction margin of 18% but calculates total margin divided by total sales as 24%. Diagnose at least two possible reasons for the difference and identify which metric should be used for overall profitability.
  2. Design Power BI measures and Tableau calculations for year-over-year sales growth when the current month is incomplete. State the assumptions and handling of missing or incomparable periods.
  3. A Tableau running total restarts for every product although management wants one chronological total for the entire business. Explain how addressing, partitioning, sorting, and the choice between a table calculation and an LOD expression affect the solution.

Multiple Choice Questions with Answers

Question 1

Which Power BI object is normally evaluated dynamically when a visual or slicer changes?

A. Calculated column

B. Measure

C. Static text box

D. Imported data type

Correct Answer: B. Measure

Question 2

In DAX, which function is primarily used to evaluate an expression after modifying filter context?

A. CALCULATE

B. COUNTROWS

C. FORMAT

D. RELATEDTABLE

Correct Answer: A. CALCULATE

Question 3

If total sales are 80,000 and total cost is 50,000, what is gross-margin percentage?

A. 30%

B. 37.5%

C. 60%

D. 62.5%

Correct Answer: B. 37.5%

Question 4

Which Tableau feature allows a user to select a value that drives a calculation?

A. Set

B. Parameter

C. Extract

D. Hierarchy

Correct Answer: B. Parameter

Question 5

Which Tableau feature is designed to calculate at an explicitly specified dimensional grain?

A. Table calculation

B. Dashboard action

C. LOD expression

D. Reference band

Correct Answer: C. LOD expression

Question 6

A running total in Tableau is generally classified as which type of calculation?

A. Table calculation

B. Data-source relationship

C. Parameter calculation

D. Row-level security rule

Correct Answer: A. Table calculation

Question 7

Why can average customer margin percentages differ from overall margin percentage?

A. Percentages always use different currencies

B. Customers may have different sales weights

C. Averages cannot be used with dimensions

D. Margin percentages cannot be aggregated

Correct Answer: B. Customers may have different sales weights

Question 8

Which design is generally most appropriate for year-to-date DAX calculations?

A. A random text field containing month names

B. A continuous and validated date table

C. A product category column

D. A manually typed list of quarters

Correct Answer: B. A continuous and validated date table

Question 9

What does a Tableau set primarily represent?

A. A subset of dimension members

B. A replacement for every measure

C. A database backup

D. A chronological date table

Correct Answer: A. A subset of dimension members

Question 10

Which practice best supports trustworthy business metrics?

A. Hide assumptions from dashboard users

B. Use different definitions on different report pages

C. Validate calculations against independent totals

D. Average all percentages regardless of grain

Correct Answer: C. Validate calculations against independent totals

Data Visualization with Power BI & Tableau
Chapter 6 of 14