diff --git a/piperider_cli/dbtutil.py b/piperider_cli/dbtutil.py index 98f252ae3..7cdd9b7bc 100644 --- a/piperider_cli/dbtutil.py +++ b/piperider_cli/dbtutil.py @@ -619,8 +619,9 @@ def _create_metric(name, filter=None, alias=None, derived_metric=None): time_grains = derived_time_grains m = Metric(metric.get('name'), - calculation_method='derived', - expression=f"{numerator.get('name')} / {denominator.get('name')}", + calculation_method='ratio', + numerator=numerator.get('name'), + denominator=denominator.get('name'), time_grains=time_grains, label=metric.get('label'), description=metric.get('description'), ref_metrics=ref_metrics, ref_id=metric.get('unique_id')) diff --git a/piperider_cli/metrics_engine/metrics.py b/piperider_cli/metrics_engine/metrics.py index d9e661b86..9b4147f7b 100644 --- a/piperider_cli/metrics_engine/metrics.py +++ b/piperider_cli/metrics_engine/metrics.py @@ -53,6 +53,8 @@ def __init__( calculation_method=None, time_grains=None, expression: str = None, + numerator: str = None, + denominator: str = None, label=None, description=None, ref_metrics=None, @@ -63,6 +65,8 @@ def __init__( self.calculation_method = calculation_method self.time_grains = time_grains self.expression = expression + self.numerator = numerator + self.denominator = denominator self.label = label self.description = description self.ref_metrics: List[Metric] = ref_metrics or [] @@ -111,7 +115,7 @@ def _compose_query_name(grain: str, dimensions: List[str], label=False) -> str: def _get_query_stmt(self, metric: Metric, grain: str, dimension: List[str], date_spine_model: CTE): metric_column_name = metric.name - if metric.calculation_method == 'derived': + if metric.calculation_method == 'derived' or metric.calculation_method == 'ratio': selectable = None # Join all parent metrics @@ -123,8 +127,11 @@ def _get_query_stmt(self, metric: Metric, grain: str, dimension: List[str], date else: selectable = join(selectable, cte, selectable.c.d == cte.c.d) - # a / b / c -> a / nullif(b, 0) / nullif(c, 0) expression = metric.expression + if metric.calculation_method == 'ratio': + expression = f"{metric.numerator}/{metric.denominator}" + + # a / b / c -> a / nullif(b, 0) / nullif(c, 0) if '/' in expression: expression_list = expression.split('/') dividend = expression_list[0]