        (membero field fields-fields)))
 
 (defn- aggregate-fieldo [{{ag-type :aggregation-type, ag-field :field} :aggregation} field]
-  (all (membero ag-type [:count :avg :sum :stddev :distinct])
-       (== field (if (contains? #{:count :distinct} ag-type)
+  (all (== field (if (contains? #{:count :distinct} ag-type)
                    {:base-type    :IntegerField
                     :field-name   :count
                     :special-type :number}
                    (-> ag-field
                        (select-keys [:base-type :special-type])
                        (assoc :field-name (if (= ag-type :distinct) :count
-                                              ag-type)))))))
+                                              ag-type)))))
+       (membero ag-type [:count :avg :sum :stddev :distinct])))
 
 (defn- valid-nameo [{:keys [result-keys]} field]
   (fresh [field-name]

(defn- matches-sort-sequenceo [l [k & more-keys]]
  (conda
   ((emptyo l))
   (s#        (if-not k
                fail
                (fresh [v1 v2 more-vals]
                  (conso v1 more-vals l)
                  (conde
                   ((== k v1)             (matches-sort-sequenceo more-vals more-keys))
                   ((firsto more-vals v2) (== k v2) fail)
                   (s#                    (matches-sort-sequenceo l more-keys))))))))

(defn- field-positiono [field v]
  (featurec field {:position v}))

(defn- fields-sorted-by-nameo [{:keys [result-keys]} f1 f2]
  (fresh [n1 n2 n1+n2]
    (featurec f1 {:field-name n1})
    (featurec f2 {:field-name n2})
    (matches-sort-sequenceo [n1 n2] (sort result-keys))))

(defn- field-groupo [query field v]
  (conda

;;     C.  Field Name
;;         When two Fields have the same :position and :special_type "group", fall back to sorting Fields alphabetically by name.
;;         This is arbitrary, but it makes the QP deterministic by keeping the results in a consistent order, which makes it testable.
(defn- fields< [query f1 f2]
  (fresh [g1 g2]
    (field-groupo query f1 g1)
    (field-groupo query f2 g2)
