Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Fix order by custom expression aggregations (#65937)

Riley Thompson41b5904d522b
diff --git a/src/metabase/driver/sql/query_processor.clj b/src/metabase/driver/sql/query_processor.clj
index fd1180efd16..c6d6fb67003 100644
--- a/src/metabase/driver/sql/query_processor.clj
+++ b/src/metabase/driver/sql/query_processor.clj
@@ -1290,6 +1290,9 @@
(defmethod ->honeysql [:sql :aggregation]
[driver [_ index]]
(driver-api/match-one (nth (:aggregation *inner-query*) index)
+ [:aggregation-options ag (options :guard driver-api/qp.add.desired-alias)]
+ (->honeysql driver (h2x/identifier :field-alias (driver-api/qp.add.desired-alias options)))
+
[:aggregation-options ag (options :guard driver-api/qp.add.source-alias)]
(->honeysql driver (h2x/identifier :field-alias (driver-api/qp.add.source-alias options)))
diff --git a/test/metabase/driver/sql/query_processor_test.clj b/test/metabase/driver/sql/query_processor_test.clj
index ab88253f084..05b67c5580e 100644
--- a/test/metabase/driver/sql/query_processor_test.clj
+++ b/test/metabase/driver/sql/query_processor_test.clj
@@ -11,6 +11,7 @@
[metabase.driver.sql.query-processor.deprecated]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.options :as lib.options]
[metabase.lib.test-metadata :as meta]
[metabase.lib.test-util :as lib.tu]
[metabase.lib.test-util.macros :as lib.tu.macros]
@@ -1626,3 +1627,24 @@
:query
(->> (driver/prettify-native-form :h2))
str/split-lines))))))
+
+(deftest ^:parallel order-by-aggregate-custom-expression-test
+ (mt/test-drivers (mt/normal-driver-select)
+ (let [mp (mt/metadata-provider)
+ orders-table (lib.metadata/table mp (mt/id :orders))
+ id-field (lib.metadata/field mp (mt/id :orders :id))
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ query (-> (lib/query mp orders-table)
+ (lib/aggregate (lib.options/update-options
+ (lib/distinct id-field)
+ assoc :name "a b"))
+ (lib/breakout (lib/with-temporal-bucket created-at :month))
+ (as-> $query
+ (lib/order-by $query
+ (m/find-first (comp #{"a b"} :name)
+ (lib/orderable-columns $query))))
+ (lib/limit 3))]
+ (is (= [1 19 37]
+ (->> (qp/process-query query)
+ (mt/formatted-rows [identity int])
+ (map second)))))))