计算HQL查询中的组数?

时间:2015-09-28 16:36:22

标签: grails hql

我有以下HQL查询:

select c.device from Choice c 
group by c.device

现在我想计算结果中的组数而不是每组的设备数。

我试过了:

select count(distinct c.device) from Choice c 
    group by c.device

但这会给出每组中不同设备的数量。这类似于[2,3,4]。但我需要2+3+4

如何获取具有HQL的组数?

1 个答案:

答案 0 :(得分:2)

您必须计算一个计数,这在HQL中是不受支持的。

SQL

在SQL中它看起来像这样:

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列进行计数。

HQL

另一种方法是进行计数,然后获得列表的大小。

Choice.executeQuery('select count(c.device) from Choice c group by c.device').size()

由于计数是在客户端完成的,因此会造成性能下降。

相关问题