scala 如何使用 slick 进行聚合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15191057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make aggregations with slick
提问by Jeriho
I want to force slick to create queries like
我想强制灵活创建查询,如
select max(price) from coffees where ...
But slick's documentationdoesn't help
但是slick 的文档没有帮助
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.
因为那些 q1-q4 不是查询,所以我无法获得结果但可以在其他查询中使用它们。
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?
生成正确的查询但已弃用(生成警告:“不推荐使用类 ColumnExtensionMethods 中的方法 max:改为使用 Query.max”)。 如何在没有警告的情况下生成这样的查询?
Another issue is to aggregate with group by:
另一个问题是与 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?
如何生成这样的查询?
回答by EECOLOR
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

