Hibernate统计一个字段的多个可能值

[b]问题[/b]:针对一张表的一个字段,想要统计其出现的不同值的次数,并封装为对象集合返回。
[b]坑点[/b]:
1.hql语句中sum()返回一个long值,所以如果定义的对象实体类字段为int型,则会报错。
2.要想日期直接用<>比较,必须保持日期格式,例如2014/01/01
[b]代码[/b]:

Query query = this
.getSession()
.createQuery(
"select hzmydCkpjsjJgmc,count(hzmydCkpjsjPjjg) as totalCommentCounts,"
+
"sum(case when hzmydCkpjsjPjjg='非常满意' then 1 else 0 end) as muchSatiCounts,"
+
"sum(case when hzmydCkpjsjPjjg='满意' then 1 else 0 end) as manuSatiCounts,"
+
"sum(case when hzmydCkpjsjPjjg='未评' then 1 else 0 end) as autoSatiCounts,"
+
"sum(case when hzmydCkpjsjPjjg='基本满意' then 1 else 0 end) as basicSatiCounts,"
+
"sum(case when hzmydCkpjsjPjjg='不满意' then 1 else 0 end) as notSatiCounts "
+ " from HzmydCkpjsj "
+ "where hzmydCkpjsjJlrq>=:startTime and hzmydCkpjsjJlrq<=:endTime "
+ "group by hzmydCkpjsjJgmc")
.setParameter("startTime", startTime)
.setParameter("endTime", endTime);
List<Object[]> list = query.list();
List<GroupHzmydCkpjsjByKs> resultList = new
ArrayList<GroupHzmydCkpjsjByKs>();
for (Object[] obj : list) {
GroupHzmydCkpjsjByKs gByKs = new GroupHzmydCkpjsjByKs();
gByKs.setTotalCommentCounts((Long) obj[1]);
gByKs.setMuchSatiCounts((Long) obj[2]);
gByKs.setManuSatiCounts((Long) obj[3]);
gByKs.setAutoSatiCounts((Long) obj[4]);
gByKs.setBasicSatiCounts((Long) obj[5]);
gByKs.setNotSatiCounts((Long) obj[6]);
gByKs.setHzmydCkpjsjJgmc(obj[0].toString());
resultList.add(gByKs);
}
return resultList;

当然,还有个简单的:

Query query = this
.getSession()
.createQuery(
"select new com.fxfk.entity.GroupHzmydCkpjsjByKs(hzmydCkpjsjJgmc,count(hzmydCkpjsjPjjg) as totalCommentCounts,"
+ "sum(case when hzmydCkpjsjPjjg='非常满意' then 1 else 0 end) as muchSatiCounts,"
+ "sum(case when hzmydCkpjsjPjjg='满意' then 1 else 0 end) as manuSatiCounts,"
+ "sum(case when hzmydCkpjsjPjjg='未评' then 1 else 0 end) as autoSatiCounts,"
+ "sum(case when hzmydCkpjsjPjjg='基本满意' then 1 else 0 end) as basicSatiCounts,"
+ "sum(case when hzmydCkpjsjPjjg='不满意' then 1 else 0 end) as notSatiCounts) "
+ " from HzmydCkpjsj "
+ "where hzmydCkpjsjJlrq>=:startTime and hzmydCkpjsjJlrq<=:endTime "
+ "group by hzmydCkpjsjJgmc")
.setParameter("startTime", startTime)
.setParameter("endTime", endTime);
List<GroupHzmydCkpjsjByKs> resultList = query.list();
return resultList;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值