[英]Perform arithmetic operation on aggregate function using Hibernate projections
I am using Hibernate 4 and I need to have an arithmetic operation done on the aggregate function. 我正在使用Hibernate 4,并且需要对聚合函数进行算术运算。 I want to use projections to achieve this.
我想使用投影来实现这一目标。 The equivalent MySQL query that I am trying to get is this:
我试图获取的等效MySQL查询是这样的:
select sum(c)/sum(bs) from my_data where pid=6 group by DATE(event_timestamp)
So far I could get the sum(c) by using the follwoing: 到目前为止,我可以通过以下方式获得sum(c):
List result= session.createCriteria(MyData.class)
.add(Restrictions.ge("eventTimestamp",fromDate)
.add(Restrictions.le("eventTimestamp",toDate)
.add(Restrictions.eq("property",p)
.setProjection(Projections.projectionList()
.add(Projections.sum("c"))
.add(Projections.sqlGroupProjection("date(evet_timestamp) as eventDate","eventDate",new String[]{"eventDate"},new Type[]{StandardBasicType.DATE})))
.addOrder(Order.asc("eventTimestamp"));
I am able to get sum(c)
with this but as you can see now I want sum(c)/sum(bs)
as the result. 我能够得到
sum(c)
,但是正如您现在看到的,我想要sum(c)/sum(bs)
作为结果。 How can I do this? 我怎样才能做到这一点?
You can use Projections.sqlProjection to introduce desired field and calculate the field value. 您可以使用Projections.sqlProjection引入所需的字段并计算字段值。 See an example here
在这里查看示例
http://technofes.blogspot.com/2011/08/hibernate-examples-step-5.html http://technofes.blogspot.com/2011/08/hibernate-examples-step-5.html
UPDATE UPDATE
add(Projections.sqlProjection("sum(c)/sum(bs) AS res",
new String[] { "res" }, new Type[] {Hibernate.INTEGER }));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.