How to make aggregations with slick

只谈情不闲聊 提交于 2019-11-29 01:46:57

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/15191057/how-to-make-aggregations-with-slick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!