计算HQL查询中的组数? [英] Count the number of groups in HQL Query?
问题描述
我有以下HQL查询:
select c.device from Choice c
group by c.device
现在我要计算结果中的组数,而不是每个组中的设备数.
Now I want to count the number of groups in the result not the number of devices per group.
我尝试过:
select count(distinct c.device) from Choice c
group by c.device
但是,这给出了每个组中不同设备的数量.这类似于 [2,3,4]
.但是我需要 2 + 3 + 4
.
but this give the number of distinct devices in each group. This is something like [2,3,4]
. But I need 2+3+4
.
如何获得HQL的组数?
推荐答案
您必须对HQL不支持的计数进行计数.
You would have to do a count of a count, which is not supported in HQL.
在SQL中,它看起来像这样:
In SQL it would look something like this:
select count(innerQuery.counted)
from (select count(d.id) as counted
from Choice c inner join Device d
on c.device_id = d.id
group by d.id) as innerQuery
在上面的示例中,外部查询从返回组的子查询中选择.然后,外部查询将对生成的 counted
列进行计数.
In the example above the outer query selects from a sub-query which returns the groups. The outer query then does a count on the generated counted
column.
一种替代方法是进行计数,然后获取列表的大小.
An alternative is to do a count and then get the size of the list.
Choice.executeQuery('select count(c.device) from Choice c group by c.device').size()
由于计数是在客户端进行的,因此会降低性能.
There's a performance penalty because the counting is done on the client-side.
这篇关于计算HQL查询中的组数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!