diff --git a/superset/connectors/sqla/models.py b/superset/connectors/sqla/models.py index 5dd885b1795ec..ff2821b9218d5 100644 --- a/superset/connectors/sqla/models.py +++ b/superset/connectors/sqla/models.py @@ -752,15 +752,11 @@ def get_sqla_query( # sqla ob = inner_main_metric_expr if timeseries_limit_metric: - if utils.is_adhoc_metric(timeseries_limit_metric): - ob = self.adhoc_metric_to_sqla(timeseries_limit_metric, cols) - elif timeseries_limit_metric in metrics_dict: - timeseries_limit_metric = metrics_dict.get( - timeseries_limit_metric, - ) - ob = timeseries_limit_metric.get_sqla_col() - else: - raise Exception(_("Metric '{}' is not valid".format(m))) + ob = self._get_timeseries_orderby( + timeseries_limit_metric, + metrics_dict, + cols, + ) direction = desc if order_desc else asc subq = subq.order_by(direction(ob)) subq = subq.limit(timeseries_limit) @@ -775,6 +771,16 @@ def get_sqla_query( # sqla tbl = tbl.join(subq.alias(), and_(*on_clause)) else: + if timeseries_limit_metric: + orderby = [( + self._get_timeseries_orderby( + timeseries_limit_metric, + metrics_dict, + cols, + ), + False, + )] + # run subquery to get top groups subquery_obj = { 'prequeries': prequeries, @@ -805,6 +811,19 @@ def get_sqla_query( # sqla return SqlaQuery(sqla_query=qry.select_from(tbl), labels_expected=labels_expected) + def _get_timeseries_orderby(self, timeseries_limit_metric, metrics_dict, cols): + if utils.is_adhoc_metric(timeseries_limit_metric): + ob = self.adhoc_metric_to_sqla(timeseries_limit_metric, cols) + elif timeseries_limit_metric in metrics_dict: + timeseries_limit_metric = metrics_dict.get( + timeseries_limit_metric, + ) + ob = timeseries_limit_metric.get_sqla_col() + else: + raise Exception(_("Metric '{}' is not valid".format(timeseries_limit_metric))) + + return ob + def _get_top_groups(self, df, dimensions, groupby_exprs): groups = [] for unused, row in df.iterrows():