如何在Slick中表达COUNT(DISTINCT ...)?
我想构建此查询的等效内容:
sql"""select formatdatetime("timestamp",'yyyy.MM.dd'), count(distinct "order_id")
from "sales" group by
formatdatetime("timestamp",'yyyy.MM.dd')""".as[(String,Option[Int])]
我试过了:
val values = sales groupBy { entry =>
formatDatetime(entry.timestamp, datetimeFormat)
} map { case(formattedDatetime, group) =>
(formattedDatetime, group.distinctOn(_.orderId).length.?)
}
抛出运行时异常:
[info] slick.SlickTreeException: Cannot convert node to SQL Comprehension
[info] | Path s9._2 : Vector[t2<{s3: Int', s4: java.sql.Timestamp', s5: scala.math.BigDecimal', s6: java.sql.Timestamp', s7: String', s8: String'}>]
(我用H2)
答案 0 :(得分:1)
到目前为止,肯定有用/我最好的拍摄:
val countDistinctOrderId = SimpleExpression.nullary[Int] { queryBuilder =>
import slick.util.MacroSupport._
import queryBuilder._
b"""count(distinct "order_id")"""
}
val values = sales groupBy { entry =>
formatDatetime(entry.timestamp, datetimeFormat)
} map { case(formattedDatetime, group) =>
(formattedDatetime, countDistinctOrderId.?)
}