使用按小时分组的休眠标准

时间:2018-01-11 08:52:50

标签: java mysql hibernate group-by hibernate-criteria

因此,我查询的参数只是日期范围。

示例参数是

startDateTime = '2018-01-10 00:00:00'
endDateTime   = '2018-01-11 00:00:00'

根据该日期范围,我希望按照日期范围的小时对计数和金额进行分组,0 - 23应该是小时的值。

以下是我的代码就是这个。

dc.add(Restrictions.ge("date", startDateTime));
dc.add(Restrictions.lt("date", endDateTime));
dc.setProjection(
    Projections.projectionList()
        .add(Projections.alias(Projections.sum("amount"), "amount"))
        .add(
            Projections.sqlProjection(
                "Cast(Count(id) as Integer) count",
                new String[]{"count"},
                new Type[]{StandardBasicTypes.INTEGER})
        )
        .add(
            Projections.sqlProjection(
                "hour(date) as date",
                new String[]{"date"},
                new Type[]{StandardBasicTypes.INTEGER})
        )       
);

结果就是这样。

[
   {
     "amount": 0.1,
     "count": 1,
     "date": 3
   }, 
   {
     "amount": 0.3,
     "count": 1,
     "date": 3
   },
   {
     "amount": 1.5,
     "count": 1,
     "date": 11
   }, 
   {
     "amount": 2.2,
     "count": 1,
     "date": 11
   },
   {
     "amount": 0.6,
     "count": 1,
     "date": 11
   }
]

知道怎么做?

1 个答案:

答案 0 :(得分:0)

您需要添加groupProperty。我不确定参数

dc.add(Restrictions.ge("date", startDateTime));
dc.add(Restrictions.lt("date", endDateTime));
dc.setProjection(
Projections.projectionList()
    .add(Projections.alias(Projections.sum("amount"), "amount"))
    .add(
        Projections.sqlProjection(
            "Cast(Count(id) as Integer) count",
            new String[]{"count"},
            new Type[]{StandardBasicTypes.INTEGER})
    )
    .add(
        Projections.groupProperty("hour(date)","date")
    )

);