首页 文章

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

提问于
浏览
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函数 .

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)
    

相关问题