diff --git a/superset/connectors/sqla/models.py b/superset/connectors/sqla/models.py index 1fcc5959ba72c..0297fd6386024 100644 --- a/superset/connectors/sqla/models.py +++ b/superset/connectors/sqla/models.py @@ -724,15 +724,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) @@ -744,6 +740,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, @@ -772,6 +778,19 @@ def get_sqla_query( # sqla return qry.select_from(tbl) + 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): cols = {col.column_name: col for col in self.columns} groups = []