回答
元々のSQLの妥当性は判断しかねますが、下記のように書けば期待しているSQLが発行されるかと思います。
def select(): Future[Seq[(String, String, Int)]] = db.run {
department
.filter(_.DepartmentCd === "1000")
.flatMap { d =>
employee
.filter(_.DepartmentCd === d.DepartmentCd)
.map(_ => (d.DepartmentCd, d.DepartmentName))
}
.groupBy { case (cd, name) => (cd, name) }
.map { case ((cd, name), group) => (cd, name, group.length) }
.result
}
実行されるSQL
select
x2."DepartmentCd", x2."DepartmentName", count(1)
from
"Department" x2,
"Employee" x3
where
(x2."DepartmentCd" = '1000') and
(x3."DepartmentCd" = x2."DepartmentCd")
group by x2."DepartmentCd", x2."DepartmentName"
蛇足
Implicit inner joinsの書き方は、公式のドキュメントを参考にすると、下記のようになります。
http://slick.lightbend.com/doc/3.1.1/sql-to-slick.html#implicit-inner-joins
department
.flatMap { d =>
employee
.filter(_.DepartmentCd === d.DepartmentCd)
.map(_ => (d.DepartmentCd, d.DepartmentName))
}
.result
select
x2."DepartmentCd", x2."DepartmentName"
from
"Department" x2,
"Employee" x3
where
(x3."DepartmentCd" = x2."DepartmentCd")
これにwhere DepartmentCd = '1000'
とgroup by
の条件をつけたものが回答のコードです。
また、.groupBy { case (cd, name) => (cd, name) }
は引数の変数をそのまま返しているだけなので、identity
を使用して下記のように書けます。
department
.filter(_.DepartmentCd === "1000")
.flatMap { d =>
employee
.filter(_.DepartmentCd === d.DepartmentCd)
.map(_ => (d.DepartmentCd, d.DepartmentName))
}
.groupBy(identity)
.map { case ((cd, name), group) => (cd, name, group.length) }
.result