Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make aggregations with slick

I want to force slick to create queries like

select max(price) from coffees where ... 

But slick's documentation doesn't help

val q = Coffees.map(_.price) //this is query Query[Coffees.type, ...]
val q1 = q.min // this is Column[Option[Double]]
val q2 = q.max
val q3 = q.sum
val q4 = q.avg 

Because those q1-q4 aren't queries, I can't get the results but can use them inside other queries.

This statement

for {
  coffee <- Coffees
} yield coffee.price.max

generates right query but is deprecated (generates warning: " method max in class ColumnExtensionMethods is deprecated: Use Query.max instead"). How to generate such query without warnings?

Another issue is to aggregate with group by:

"select name, max(price) from coffees group by name"

Tried to solve it with

for {
  coffee <- Coffees
} yield (coffee.name, coffee.price.max)).groupBy(x => x._1)

which generates

select x2.x3, x2.x3, x2.x4 from (select x5."COF_NAME" as x3, max(x5."PRICE") as x4 from "coffees" x5) x2 group by x2.x3

which causes obvious db error

column "x5.COF_NAME" must appear in the GROUP BY clause or be used in an aggregate function

How to generate such query?

like image 765
Jeriho Avatar asked Mar 03 '13 21:03

Jeriho


1 Answers

As far as I can tell is the first one simply

Query(Coffees.map(_.price).max).first

And the second one

val maxQuery = Coffees
  .groupBy { _.name }
  .map { case (name, c) =>
    name -> c.map(_.price).max
  }

maxQuery.list

or

val maxQuery = for {
  (name, c) <- Coffees groupBy (_.name)
} yield name -> c.map(_.price).max

maxQuery.list
like image 106
EECOLOR Avatar answered Sep 23 '22 03:09

EECOLOR