In this blog, we have learnt how to use custom column. But in certain cases we may want to pass multiple filter conditions and do calculation’s in custom column. For example, we want to find out sales ration wherein in numerator = total sales when sale type is domestic divided by denominator = total sales when sale type = international.
This is not a very straightforward use case. In this blog we will learn how to do the same.
1. Use Case 1 – Divide Conditional Aggregated Values
This use case creates a Custom Column that calculates the ratio below ratio
sum of travel cost when location is Ambala
The calculation uses conditional aggregation so that only rows matching each destination contribute to the corresponding total.
Create a custom column. Read this blog to learn how to create custom column. In the custom column, put the below expression.
Custom Column expression
(
SUM(
CASE
WHEN destination = 'Agra'
THEN "travel_details"."travel_cost"
ELSE 0
END
)
)
/
(
SUM(
NULLIF(
CASE
WHEN destination = 'Ambala'
THEN "travel_details"."travel_cost"
ELSE 0
END,
0
)
)
)
How the expression works
Agra total (numerator): The CASE condition includes travel_cost only when destination is Agra. All other destinations contribute 0. SUM adds the qualifying costs.
Ambala total (denominator): The second CASE condition includes travel_cost only when destination is Ambala. SUM adds those costs.
NULLIF protection: NULLIF converts a zero value to NULL. This prevents a division-by-zero error when the Ambala total is zero.
Final division: The Agra total is divided by the Ambala total to return the ratio.
Example result
| Destination | Total travel cost |
|---|---|
| Agra | 18,400 |
| Ambala | 3,100 |
| Agra ÷ Ambala | 18,400 ÷ 3,100 = 5.93548 |
approximately 5.93548. This means the Agra travel cost is approximately 5.94 times the Ambala travel cost.
