Slick 3 dynamic groupby - fields from its List[Str

2019-05-30 19:54发布

Lets say i want to execute the query:

select columnName1,columnName2,Sum(*)
from table
group by columnName1,columnName2

where columnName1,columnName2 is supplied from list[string] ("columnName1",columnName2")

how can i do it with slick? if the columns are known by compile time, i can easily use the groupBy function:

tableQuery.groupBy { r => (r.columnName1,r.columnName2)}.map (case groupName,group) => (groupName._1,groupName._2,group.map(...).avg)}

but what about dynamic?

2条回答
倾城 Initia
2楼-- · 2019-05-30 20:31

You can use the r.column("foo") syntax to access columns dynamically at runtime, so I believe you can just do something like the following?

columnNames = List("col1", "col2")
tableQuery
    .groupBy(r => columnNames.map(name => r.column(name)))
    .map({ case (groupName, group) => /* do something with it */})
查看更多
戒情不戒烟
3楼-- · 2019-05-30 20:47

To convert a string column name to Rep type, you can use the Slick AST Library. I had a similar requirement and done it using the AST Library. You can refer to this code, which does the same thing. I also followed the same code to solve my requirement.

查看更多
登录 后发表回答