           ON
             sort_table.x = data_table.x
           ORDER BY %5$s, data_table.s"
-          (:columnName bucket-column)
+          (sql-option-bucket-column bucket-column)
           aggregation
           table-name
           filter-sql

           FROM (SELECT %1$s as x, %2$s FROM %3$s WHERE %4$s GROUP BY x)z
           ORDER BY %5$s 
           LIMIT %6$s"
          (:columnName bucket-column)
          aggregation
          table-name
          filter-sql

    nil   "x ASC"
    "asc" (format "%s ASC NULLS FIRST" column)
    "dsc" (format "%s DESC NULLS LAST" column)))

(defn- sql-option-bucket-column [bucket-column]
  (if (= "option" (:type bucket-column))
    (format "unnest(regexp_split_to_array(%1$s,'\\|'))" (:columnName bucket-column))
    (:columnName bucket-column)))

(defn- subbucket-sql [table-name bucket-column subbucket-column aggregation filter-sql sort-sql truncate-size]
  (format "
