Spring 如何划分两个HQL计数结果?

Spring 如何划分两个HQL计数结果?,spring,hibernate,grails,hql,grails-2.0,Spring,Hibernate,Grails,Hql,Grails 2.0,我想计算不活跃人群的百分比除以活跃人群的百分比 我将执行类似以下HQL查询的操作,但它不起作用: (select count(x) from People as x where x.active=false) / (select count(x) from People as x where x.active=true) 我该怎么做呢?您可以使用GROUPBY子句来表示这一点。以下是如何在Grails中实现这一点: def countByAction = People. execut

我想计算不活跃人群的百分比除以活跃人群的百分比

我将执行类似以下HQL查询的操作,但它不起作用:

(select count(x) from People as x where x.active=false) / 
(select count(x) from People as x where x.active=true)

我该怎么做呢?

您可以使用GROUPBY子句来表示这一点。以下是如何在Grails中实现这一点:

def countByAction = People.
    executeQuery("select active, count(*) from People group by active")*.
    toList().
    collectEntries{it}
println (countByAction[true])
println (countByAction[false])

因为您使用的是HQL表达式,所以我假设您使用的是Hibernate。在这种情况下,我建议您使用
@Formula
注释。您可以在此处找到其他信息:


类似的方法应该可以奏效

String hql = "select count(x)/(select count(x) from People as x where x.active=true) 
                 from People as x where x.active=false";

Long result = (Long) em.createQuery(hql).getSingleResult();

注意:以上未经测试

我使用countBy*动态方法,该方法使用域类的属性来查询匹配记录数的计数。参见

什么不起作用?如果你得到一个NPE,它可能来自Hi ataylor,我不明白这个。。。它是否符合用户的要求?您可以添加一个如何工作的描述吗?它使用HQL group by子句将查询结果拆分为多个组。特别是,它按
active
列进行分组。由于
active
是一个布尔字段,它将结果分为两组,分别为true和false。
count(*)
选择每组中记录的计数。查询的结果类似于
[[true,10],[false,20]]
。这可能有助于理解HQL/SQL中的分组: