2

给定以下实体类和带有相关表的 postgres 数据库:

case class Statistics(name: String, 
                      measure: Long, 
                      datetime: Timestamp = new Timestamp(System.currentTimeMillis))

我如何构造一个 Squeryl 聚合查询,该查询返回每天或每周的度量计数或其累积值,基本上导致 SQL 语句类似于:

select count(*), date_trunc('day',datetime) from stats
       group by date_trunc('day',datetime);
select sum(*), date_trunc('day',datetime) from stats
       group by date_trunc('day',datetime);

使用无法从 Squeryl 直接访问的 postgres 的date_trunc函数。

4

1 回答 1

1

可以使用自定义函数映射生成所需的查询:

class DateTrunc(span: String, 
                e: DateExpression[Timestamp], 
                m: OutMapper[Timestamp])
extends FunctionNode[Timestamp]("date_trunc", 
                     Some(m), 
                     Seq(new TokenExpressionNode("'"+span+"'"), e))
with DateExpression[Timestamp]

def dateTrunc(span: String, 
              e: DateExpression[Timestamp])
             (implicit m: OutMapper[Timestamp]) = new DateTrunc(span,e,m)

然后可以在实际查询中使用它,例如:

def historyQuery(name: String, 
                          span: String = "day", 
                          pageSize: Int = 10) = from(table) (
    stats =>
        where(stats.name === name)
        groupBy(dateTrunc(span,stats.datetime))
        compute(count)
        orderBy(dateTrunc(span,stats.datetime) desc)
) page(0,pageSize)
于 2013-07-23T11:50:09.780 回答