CASE is a conditional statement that performs logical tests on a series of conditions and returns values when a condition is met. The CASE function returns a numeric result. You use CASE for complex conditional expressions that contain two or more conditions.
CASE is followed by WHEN/THEN keywords to specify the conditions, then by ELSE to specify the default return.
If no match is found, the default return expression (ELSE) is used. If there is no default return and no values match, then Null is returned. All CASE expressions conclude with the END keyword.
CASE and Multidimensionality
Before proceeding to the CASE syntax samples, as a user you have to understand that usage guidelines for CASE in the MAQL environment (see MAQL - Analytical Query Language) are based on multidimensionality. Understanding multidimensionality is crucial to ensure your CASE metrics return correct results (see MAQL and Multidimensionality).
- CASE does not work with the base data level.
- Instead, the condition is evaluated on the aggregation dimension.
- All WHENs are evaluated independently but all based on a single dimension (the aggregation dimension mentioned in the previous point).
To ensure can identify any errors in your metrics that use the CASE statement early, we recommend the following:
- Always put the CASE statement inside an aggregation (SUM) container.
Avoid using nested CASE statements in metrics. A CASE statement forces calculations to be done for every single attribute that meets that condition. Anything that does not match the CASE conditions reaches its ELSE clause and has to be processed as well.
CASE can be used in the following two syntax forms:
Using the aggregation container ensure that the CASE conditions are computed on the correct dimension and returns relevant results.
This is why we recommend using SUM-based aggregation in the XAE3 environment.
How to Use CASE Correctly
As noted above, we advise you to use CASE inside aggregation containers.
Here is an example of incorrect use of CASE in the following logical data model. For the sake brevity, only one CASE condition is used.
If you want to slice the following metric with Campaign Category, the insight would not compute in XAE3 because the WHEN conditions are not related to the insight’s dimensionality:
SELECT CASE WHEN Customer State IN (AR, NY) THEN SUM (Price) ELSE SUM (Price*Quantity) END
On the other hand, the same metric when sliced by attribute Customer ID (instead of Campaign Category) is valid. That is because the slicing attribute (Customer ID) is directly related to the CASE condition attribute (Customer State).
If you need to slice by unrelated attribute, put the CASE statement inside the SUM aggregation instead:
SELECT SUM (SELECT CASE WHEN Customer State IN (AR, NY) THEN Price ELSE Price*Quantity END)