The Tableau CASE
and WHEN
keyword is used to create a logical statement with your dimension or measure variable(s) to see if it match a certain condition(s).
When the specified condition occurs, CASE
will return the value you specify as the return value in the statement.
You can have one or more conditions when defining the CASE
function as your calculated field formula.
Let’s see an example of using the CASE
function to create a calculated field.
The following dataset contains sales records of a fictional office supplies company:
There’s a City
dimension variable in the dataset that shows in what city the sales is recorded:
City:
- Edinburgh
- London
- Newcastle
Using Tableau WHEN
function, you can encode the cities using numbers as follows:
Edinburgh
encoded as1
London
encoded as2
Newcastle
encoded as3
Right-click anywhere on the Data pane and select the Create Calculated Field… option.
Name the Calculated Field as Encoded City
and write the following formula into the field:
CASE [City] WHEN "Edinburgh" THEN 1
WHEN "London" THEN 2
WHEN "Newcastle" THEN 3 END
The above CASE
statement reads:
- When the
City
value equalsEdinburgh
then return1
- When the
City
value equalsLondon
then return2
- When the
City
value equalsNewcastle
then return3
The CASE
function also requires the END
keyword to indicate the end of the function.
Since you’re creating a dimensional calculated field, you need to right-click on the Encoded City
variable and select Convert to Dimension.
Finally, drag the Encoded City
and the City
variables into the Rows shelf of your Sheet.
You’ll see the table output generated as follows:
As you can see, the City
values have been encoded using the CASE
function with multiple conditions.
You can also replace the third WHEN
statement with an ELSE
statement like this:
CASE [City] WHEN "Edinburgh" THEN 1
WHEN "London" THEN 2
ELSE 3 END
The ELSE
statement will be considered as the default return value should the WHEN
conditions are not fulfilled.
If you want to inspect the calculated field, you can view and download the Workbook for this tutorial here:
And that’s how you can use the CASE
- WHEN
statement in Tableau. Good work! 👍