Squeryl:如何使用postgres创建聚合查询'日期列上的date_trunc()函数

时间:2013-07-23 07:36:15

标签: postgresql squeryl

给出以下实体类和带有相关表的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函数。

1 个答案:

答案 0 :(得分: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)