How to select max, min in same query in slick
Asked Answered
R

1

11

I want to do this SELECT MAX(age), MIN(age) FROM users WHERE name = 'Rick'. The best I came up with involves 2 queries: Users.filter(_.name === 'Rick').map(_.age).max

Rolanderolando answered 20/11, 2014 at 21:12 Comment(0)
J
9

This is supported, but first, you'll need to group it. Since you're treating the entire set as a group, group it by true and slick will ignore it when generating the SQL:

val q = Users.filter(_.name === 'Rick').groupBy { _ => true }.map {
  case (_, group) =>
    (group.map(_.age).max, group.map(_.age).min)
}

It should yield you something like this:

q.selectStatement
# => select max(x2."age"), min(x2."age") from "Users" x2

Another approach you might try would be a union.

Joe answered 21/11, 2014 at 6:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.