Calculated Fields Fundamentals
Calculated Fields Fundamentals
A calculated field in Tableau is a new field you create by defining a formula that operates on existing fields in your data source. Unlike fields that come directly from your database, calculated fields are computed by Tableau at query time, giving you the power to reshape, combine, and derive values without modifying the underlying data.
Why Calculated Fields Matter
Raw data rarely arrives in the shape your analysis needs. A sales table might store revenue and cost separately but not profit. A dates table might store timestamps but not the fiscal quarter. A customer table might store full names but not the first name for personalization. Calculated fields close the gap between what the data provides and what the analysis demands.
The critical advantage is that calculated fields are dynamic. When a user filters a dashboard, the calculation re-evaluates against the filtered data. A static column in a database cannot do this. This makes calculated fields the primary mechanism for building responsive, interactive dashboards.
Types of Calculated Fields
Tableau supports four broad categories of calculations:
- Basic calculations — arithmetic operations, string manipulations, date functions, and logical expressions applied row by row.
- Level of Detail (LOD) expressions — calculations computed at a granularity different from the visualization's level of detail.
- Table calculations — calculations computed on the aggregated data in the view, after Tableau has rendered the visualization.
- Parameters — user-defined inputs that make calculations interactive.
Creating a Basic Calculated Field
To create a calculated field, right-click in the Data pane and select "Create Calculated Field." The calculation editor opens with a formula bar, a list of available functions, and a reference to the fields in your data source.
// Profit margin as a percentage
SUM([Profit]) / SUM([Revenue])
// Categorize customers by spending tier
IF [Total Spend] >= 10000 THEN "VIP"
ELSEIF [Total Spend] >= 5000 THEN "Premium"
ELSE "Standard"
END
// Extract year from a date
YEAR([Order Date])
// Concatenate first and last name
[First Name] + " " + [Last Name]
// Days between order and shipment
DATEDIFF('day', [Order Date], [Ship Date])
Row-Level vs. Aggregate Calculated Fields
A calculated field can operate at the row level or the aggregate level. A row-level calculation computes a value for each individual record. An aggregate calculation computes a value across a group of records.
// Row-level: profit per transaction
[Sales] - [Cost]
// Aggregate: total profit across all transactions
SUM([Sales]) - SUM([Cost])
The distinction matters because Tableau applies filters differently. Row-level calculations are computed before dimension filters are applied. Aggregate calculations are computed after. If you need a calculation to respect a filter, use an aggregate. If you need it to ignore a filter, use a row-level calculation or an LOD expression.
Common Functions by Category
String functions: LEFT, RIGHT, MID, LEN, TRIM, UPPER, LOWER, CONTAINS, STARTSWITH, SPLIT, REPLACE
Date functions: YEAR, MONTH, DAY, DATEPART, DATENAME, DATEDIFF, DATEADD, TODAY, NOW, MAKEDATE
Logical functions: IF, ELSEIF, ELSE, END, CASE, IIF, IFNULL, ISNULL, AND, OR, NOT
Aggregate functions: SUM, AVG, MIN, MAX, COUNT, COUNTD, STDEV, VAR, MEDIAN
Math functions: ABS, ROUND, CEILING, FLOOR, SQRT, POWER, LOG, EXP, PI, DIV, MOD
Best Practices
- Name fields descriptively.
Profit Margin %is better thanCalc1. - Use comments for complex logic. Tableau supports
//comments in calculations. - Validate against known values. Spot-check your calculation against a manual computation.
- Avoid nested IF chains with more than 5 branches. Use
CASEstatements or lookup tables instead. - Document assumptions. If a calculation assumes a specific business rule, note it in the description.
Dimension and Measure Calculations
Dimension and Measure Calculations
In Tableau, every field is either a dimension or a measure. Dimensions are categorical fields that segment data — regions, product categories, customer segments. Measures are numeric fields that can be aggregated — sales, profit, quantity. Calculated fields can be either, and the choice affects how Tableau treats them in visualizations.
Creating Dimension Calculations
A dimension calculation produces a categorical result. The most common pattern is a calculated field that groups records into buckets or categories.
// Segment customers by order frequency
IF COUNTD([Order ID]) >= 10 THEN "Frequent"
ELSEIF COUNTD([Order ID]) >= 3 THEN "Regular"
ELSE "Occasional"
END
// Group products by price range
CASE [Unit Price]
WHEN 0 THEN "Budget"
WHEN 25 THEN "Economy"
WHEN 75 THEN "Mid-Range"
ELSE "Premium"
END
// Extract the month name for a custom sort order
DATENAME('month', [Order Date])
// Create a binary flag for filtering
IF [Region] = "West" THEN "West Region"
ELSE "Other Regions"
END
Dimension calculations are placed on the Rows or Columns shelf, or used as filters and color encodings. They partition the view into discrete segments.
Creating Measure Calculations
A measure calculation produces a numeric result that can be aggregated. The most common pattern is a ratio, a running total, or a comparison.
// Profit margin
SUM([Profit]) / SUM([Sales])
// Year-over-year growth
(SUM([Sales]) - LOOKUP(SUM([Sales]), -1)) / ABS(LOOKUP(SUM([Sales]), -1))
// Running total of sales
RUNNING_SUM(SUM([Sales]))
// Percent of total
SUM([Sales]) / TOTAL(SUM([Sales]))
// Rank by sales
RANK(SUM([Sales]), 'desc')
Measure calculations are placed on the Rows or Columns shelf and aggregated using SUM, AVG, or another aggregation function.
Converting Between Dimensions and Measures
Tableau allows you to convert a calculated field from dimension to measure or vice versa. Right-click the field and select "Convert to Dimension" or "Convert to Measure." This is useful when a calculation produces a numeric result that you want to use as a category (e.g., bucketing ages into ranges) or when a calculation produces a string that you want to treat as a measure (e.g., counting distinct values).
The Role of Aggregation
Every measure calculation must specify an aggregation. Tableau does not allow unaggregated measures in most visualizations. The aggregation determines how values are combined before the calculation is applied.
// Average profit per order
AVG([Profit])
// Total profit across all orders
SUM([Profit])
// Count of distinct customers
COUNTD([Customer ID])
// Median order value
MEDIAN([Order Value])
The choice of aggregation changes the result. AVG([Profit]) computes the average profit per row. SUM([Profit]) / COUNT([Order ID]) computes the average profit per order. These are different if some orders have multiple rows.
Practical Example: Customer Segmentation Dashboard
Suppose you are building a customer segmentation dashboard. You need calculated fields for:
- Customer tier (dimension):
IF [Total Spend] >= 10000 THEN "VIP" ELSEIF [Total Spend] >= 5000 THEN "Premium" ELSE "Standard" END - Days since last order (measure):
DATEDIFF('day', MAX([Order Date]), TODAY()) - Average order value (measure):
SUM([Sales]) / COUNTD([Order ID]) - Customer lifetime (measure):
DATEDIFF('month', MIN([Order Date]), MAX([Order Date]))
Each calculated field serves a specific analytical purpose. The dimension calculation segments customers. The measure calculations quantify behavior. Together they enable a dashboard that answers: Who are our most valuable customers? How recently have they ordered? How much do they spend per order? How long have they been with us?
Common Pitfalls
- Mixing aggregated and unaggregated fields.
SUM([Sales]) - [Cost]is invalid because[Cost]is unaggregated. UseSUM([Sales]) - SUM([Cost]). - Using the wrong aggregation for the question.
AVG([Profit])gives the average profit per row, not per order. - Forgetting to handle division by zero. Use
IF SUM([Sales]) = 0 THEN 0 ELSE SUM([Profit]) / SUM([Sales]) END. - Creating a dimension calculation that should be a measure. If you bucket ages into ranges, the result is a dimension. If you count customers in each bucket, that count is a measure.
Level of Detail (LOD) Expressions
Level of Detail (LOD) Expressions
Level of Detail (LOD) expressions are the most powerful feature in Tableau's calculation language. They let you compute values at a granularity different from the visualization's level of detail, without changing the view's structure. This solves a class of problems that would otherwise require complex table calculations or data source modifications.
The Problem LOD Solves
Suppose your visualization shows monthly sales by region. You want to add a reference line showing the average monthly sales across all regions. A simple AVG(SUM([Sales])) computes the average of the monthly totals, not the average across all months and regions. You need to compute the average at a different granularity — the overall level — while keeping the view at the monthly-by-region level.
LOD expressions solve this by explicitly specifying the granularity of the computation.
Fixed LOD
A FIXED LOD computes a value using only the dimensions you specify, ignoring the visualization's dimensions entirely.
// Total sales per region, regardless of what's in the view
{FIXED [Region] : SUM([Sales])}
// Total sales across all regions and months
{FIXED : SUM([Sales])}
// Average monthly sales per region
{FIXED [Region] : AVG({FIXED [Region], [Month] : SUM([Sales])})}
The FIXED LOD is the most common type. It answers questions like: "What is each region's total sales, regardless of how the view is filtered?" or "What is the overall average, regardless of the visualization's dimensions?"
Include LOD
An INCLUDE LOD computes a value at a finer granularity than the visualization. It adds dimensions to the computation that are not in the view.
// Average sales per customer within each region
{INCLUDE [Customer ID] : AVG([Sales])}
// Total sales per product category within each region
{INCLUDE [Product Category] : SUM([Sales])}
Use INCLUDE when you need to compute an aggregate at a more detailed level and then roll it up. For example, to compute the average order value per customer within each region, you INCLUDE the customer dimension.
Exclude LOD
An EXCLUDE LOD computes a value at a coarser granularity than the visualization. It removes dimensions from the computation.
// Total sales by region, excluding the month dimension
{EXCLUDE [Month] : SUM([Sales])}
// Percent of region's total sales
SUM([Sales]) / {EXCLUDE [Month] : SUM([Sales])}
Use EXCLUDE when you need to compute a percentage of total or a running total that ignores certain dimensions.
LOD Evaluation Order
LOD expressions are evaluated after dimension filters but before measure filters. This means:
- A
FIXEDLOD respects dimension filters applied to the view. - A
FIXEDLOD ignores measure filters (filters on aggregated values). - A
FIXEDLOD ignores table calculations.
This evaluation order is critical for understanding when to use LODs versus table calculations. If you need a calculation that respects a dimension filter, use a FIXED LOD. If you need a calculation that ignores a dimension filter, use a table calculation or a context filter.
Practical Example: Cohort Analysis
Suppose you want to analyze customer cohorts by their first purchase month. You need to compute each customer's first purchase month, then group customers by that month, and finally compute metrics for each cohort.
// First purchase month for each customer
{FIXED [Customer ID] : MIN(DATETRUNC('month', [Order Date]))}
// Cohort size (number of customers in each cohort)
COUNTD([Customer ID])
// Average revenue per customer in each cohort
{FIXED [First Purchase Month] : AVG({FIXED [Customer ID] : SUM([Sales])})}
The first LOD computes the cohort assignment. The second counts customers per cohort. The third computes the average revenue per customer within each cohort, using a nested LOD to first compute each customer's total revenue, then average across customers in the cohort.
Common Pitfalls
- Using
FIXEDwhen you needINCLUDE.FIXEDignores the view's dimensions.INCLUDEadds to them. Choose based on whether you want to ignore or extend the view's granularity. - Forgetting that
FIXEDrespects dimension filters. If you need a calculation that ignores a filter, use a context filter or a table calculation. - Nesting LODs incorrectly. The inner LOD must be fully contained within the outer LOD's granularity.
- Using LODs for simple aggregations. If a simple
SUMorAVGsuffices, use it. LODs add complexity and computational cost.
When to Use Each LOD Type
| LOD Type | Use When | Example |
|---|---|---|
FIXED |
Compute at a specific granularity, ignoring the view | Total sales per region |
INCLUDE |
Compute at a finer granularity than the view | Average order value per customer |
EXCLUDE |
Compute at a coarser granularity than the view | Percent of total sales |
Table Calculations
Table Calculations
Table calculations are computed on the aggregated data in the view, after Tableau has rendered the visualization. They operate on the result set, not the underlying data. This makes them powerful for relative comparisons — running totals, percent of total, rankings, and period-over-period changes — but also means they are sensitive to the view's structure.
How Table Calculations Work
When Tableau renders a visualization, it produces a result set — a table of aggregated values. Table calculations operate on this table. The calculation is applied across the cells of the table, using the dimensions in the view to determine the direction and scope of the computation.
For example, a running total computes a cumulative sum across the cells in a partition. The partition is defined by the dimensions in the view. If the view has Region on Rows and Month on Columns, the running total computes across months within each region.
Common Table Calculations
// Running total of sales
RUNNING_SUM(SUM([Sales]))
// Percent of total sales
SUM([Sales]) / TOTAL(SUM([Sales]))
// Rank by sales (descending)
RANK(SUM([Sales]), 'desc')
// Year-over-year growth
(SUM([Sales]) - LOOKUP(SUM([Sales]), -1)) / ABS(LOOKUP(SUM([Sales]), -1))
// Moving average (3 periods)
WINDOW_AVG(SUM([Sales]), -2, 0)
// Difference from previous period
SUM([Sales]) - LOOKUP(SUM([Sales]), -1)
// Percent difference from previous period
(SUM([Sales]) - LOOKUP(SUM([Sales]), -1)) / ABS(LOOKUP(SUM([Sales]), -1))
Partitioning and Addressing
Table calculations are controlled by two concepts: partitioning and addressing.
- Partitioning defines the groups within which the calculation is computed. Each partition is an independent scope.
- Addressing defines the direction of the calculation within each partition.
By default, table calculations use the view's dimensions for both partitioning and addressing. You can override this by clicking the calculation in the view and selecting "Edit Table Calculation."
For example, if you have Region and Month in the view, and you want a running total across months within each region, the default partitioning (by region) and addressing (by month) is correct. If you want a running total across regions within each month, you need to swap the addressing.
Table Calculations vs. LOD Expressions
Table calculations and LOD expressions can sometimes produce the same result, but they differ in important ways:
| Aspect | Table Calculation | LOD Expression |
|---|---|---|
| Computation timing | After aggregation | During query |
| Sensitivity to view | High — changes with view structure | Low — independent of view |
| Filter interaction | Ignores dimension filters | Respects dimension filters |
| Performance | Computed on result set | Computed on data source |
| Use case | Relative comparisons | Absolute comparisons at specific granularity |
Choose table calculations for relative comparisons that depend on the view's structure. Choose LOD expressions for absolute comparisons that must be independent of the view.
Practical Example: Sales Dashboard
Suppose you are building a sales dashboard with Region on Rows and Month on Columns. You want to show:
- Monthly sales (measure):
SUM([Sales]) - Running total (table calculation):
RUNNING_SUM(SUM([Sales])) - Percent of total (table calculation):
SUM([Sales]) / TOTAL(SUM([Sales])) - Rank (table calculation):
RANK(SUM([Sales]), 'desc') - Year-over-year growth (table calculation):
(SUM([Sales]) - LOOKUP(SUM([Sales]), -1)) / ABS(LOOKUP(SUM([Sales]), -1))
Each table calculation serves a specific analytical purpose. The running total shows cumulative performance. The percent of total shows relative contribution. The rank shows competitive position. The year-over-year growth shows trend.
Common Pitfalls
- Forgetting to set the addressing. The default addressing may not match your analytical intent. Always verify the direction of the calculation.
- Using table calculations for absolute values. Table calculations are relative to the view. Use LOD expressions for absolute values.
- Applying table calculations to filtered data. Table calculations ignore dimension filters. If you need the calculation to respect a filter, use a context filter or an LOD expression.
- Overusing table calculations. They are computed on the result set, which can be slow for large datasets. Use LOD expressions when possible.
Practice Problems
Create a calculated field that computes profit margin as a percentage. The data source has fields [Sales] and [Cost]. Handle the case where sales is zero.
Solution
IF SUM([Sales]) = 0 THEN 0
ELSE (SUM([Sales]) - SUM([Cost])) / SUM([Sales])
END Create a FIXED LOD expression that computes total sales per customer, regardless of what dimensions are in the visualization. Then use it to compute each customer's share of total sales.
Solution
// Total sales per customer (FIXED LOD)
{FIXED [Customer ID] : SUM([Sales])}
// Customer share of total sales
{FIXED [Customer ID] : SUM([Sales])} / {FIXED : SUM([Sales])} Create a table calculation that computes a running total of sales across months within each region. The view has Region on Rows and Month on Columns.
Solution
RUNNING_SUM(SUM([Sales])) Quiz
1. What is the key difference between a row-level calculated field and an aggregate calculated field?
2. Which LOD expression computes a value at a finer granularity than the visualization?
3. When are table calculations computed?
Flashcards
Question
What is the difference between a dimension calculation and a measure calculation?
Click to reveal answer
Answer
A dimension calculation produces a categorical result (e.g., customer tier, price range) and is used to segment data. A measure calculation produces a numeric result (e.g., profit margin, running total) and is aggregated using SUM, AVG, etc.
Question
What does a FIXED LOD expression do?
Click to reveal answer
Answer
A FIXED LOD computes a value using only the dimensions you specify, ignoring the visualization's dimensions entirely. Example: {FIXED [Region] : SUM([Sales])} computes total sales per region regardless of what's in the view.
Question
When should you use a table calculation vs. an LOD expression?
Click to reveal answer
Answer
Use table calculations for relative comparisons that depend on the view's structure (running totals, percent of total, rankings). Use LOD expressions for absolute comparisons that must be independent of the view (totals at a specific granularity).
Question
What is the evaluation order of LOD expressions relative to filters?
Click to reveal answer
Answer
LOD expressions are evaluated after dimension filters but before measure filters. This means FIXED LODs respect dimension filters but ignore measure filters and table calculations.
Revision Notes
Key Takeaways
- 1. Calculated fields bridge the gap between raw data and analytical needs
- 2. Dimension calculations segment data; measure calculations quantify it
- 3. LOD expressions compute at a granularity different from the visualization
- 4. FIXED LODs ignore view dimensions; INCLUDE adds to them; EXCLUDE removes from them
- 5. Table calculations operate on the result set and are sensitive to view structure
- 6. Choose table calculations for relative comparisons, LODs for absolute comparisons
Interview Tips
- • Explain when to use a FIXED LOD vs. a table calculation
- • Describe the evaluation order of calculated fields relative to filters
- • Demonstrate how to handle division by zero in calculated fields
- • Show how to use LODs for cohort analysis or customer segmentation
Cheat Sheet
Cheat Sheet: Tableau Calculated Fields
Calculation Types
- Basic: Row-level or aggregate formulas
- LOD: Compute at different granularity
- Table: Compute on result set after rendering
LOD Syntax
{FIXED [Dim] : Aggregation}— ignore view dimensions{INCLUDE [Dim] : Aggregation}— add dimensions to view{EXCLUDE [Dim] : Aggregation}— remove dimensions from view
Common Table Calculations
RUNNING_SUM(SUM([Sales]))— cumulative totalSUM([Sales]) / TOTAL(SUM([Sales]))— percent of totalRANK(SUM([Sales]), 'desc')— rankingLOOKUP(SUM([Sales]), -1)— previous valueWINDOW_AVG(SUM([Sales]), -2, 0)— moving average
Key Rules
- Row-level calcs: computed before dimension filters
- Aggregate calcs: computed after dimension filters
- LODs: respect dimension filters, ignore measure filters
- Table calcs: computed on result set, sensitive to view structure