Search code examples
kotlinkotlin-exposed

Aliasing count() for several columns in a group by query in Exposed


I'm trying to create a query like the presented one in the ORM Exposed.

select t.a, t.b, count(*)
from table as t
group by t.a, t.b;

But it seems that .count() supports aliases only for one column, but here I need two columns:

val count = Table.Table.<somehow I need to push both fields a and b here>.count()

Table.Table
  .slice(Table.Table.a, Table.Table.b, count)
  .selectAll()
  .groupBy(Table.Table.a, Table.Table.b)
  .map { row ->
   Result(
     state = row[Table.Table.a],
     trigger = row[Table.Table.b],
     count = row[count]
   )
  }

Are you have any ideas on how to do it?


Solution

  • val count = Count(stringLiteral("*"))
    

    This will generate COUNT('*') in your query (which is a valid SQL expression, giving the same result as COUNT(*)).

    If you want to get rid of these annoying quotes, you may do the following:

    val asterisk = object : Expression<String>() {
        override fun toQueryBuilder(queryBuilder: QueryBuilder) {
            queryBuilder { +"*" }
        }
    }
    val count = Count(asterisk)