简体   繁体   English

Hibernate Criteria:使用group by子句计划Count

[英]Hibernate Criteria: Projecting Count with group by clause

I want to execute the following SQL 我想执行以下SQL

select count(*) as myCount from user group by name;

I came up with the following criteria for the same 我想出了同样的以下标准

DetachedCriteria.ForClass(typeof(UserDTO))
    .setProjections(Projections.ProjectionList()
                        .Add(Projections.rowCount(),"myCount")
                        .Add(Projections.groupProperty("this.name"));

I get the result back as pair of the count and name,How can I get just the count from this. 我将结果作为计数和名称的对返回,我怎样才能从中获得计数。

You can use count distinct if there is only one group by column. 如果列中只有一个组,则可以使用count distinct。

HQL: HQL:

select count(distinct name) as myCount from user

Criteria: 标准:

DetachedCriteria.ForClass(typeof(UserDTO))
.setProjections(Projections.ProjectionList()
                    .Add(Projections.countDistinct("name"),"myCount"));

I don't think you can do it with Criteria, but it's easy with HQL. 我不认为你能用Criteria做到这一点,但是用HQL很容易。 It's exactly the same string as your SQL query, but with entity/property names instead of table/column ones. 它与您的SQL查询完全相同,但使用实体/属性名称而不是表/列名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM