---
title: "聚合函数排序"
author: "east_java"
date: "2009-04-27T22:49:40Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-04-27T22:49:40Z"
id: 375816
url: "https://japi.iteye.com/blog/375816"
---

要对聚合函数进行排序：

使用SQL:
select prdid , count(*) from order group by prdid order by count(*) desc 

这样子应该是没有问题的。。

我的类里面有个引用类：
select user ,count(*) from Ann group by user ordery by count(*)
其中user为类。
这样子写之后呢，老是提示没有user.id 错误。不包括在group by中

很是郁闷。。

所以只能用HQL试试。。

> List results = session.createCriteria(Cat.class)
>     .setProjection( Projections.projectionList()
>         .add( Projections.rowCount(), "catCountByColor" )
>         .add( Projections.avg("weight"), "avgWeight" )
>         .add( Projections.max("weight"), "maxWeight" )
>         .add( Projections.groupProperty("color"), "color" )
>     )
>     .addOrder( Order.desc("catCountByColor") )
>     .addOrder( Order.desc("avgWeight") )
>     .list();


这样子写就成功了。。

很是奇怪啊。。

所以以后写查询还是使用框架提供对应的查询语句。
一是为了移植性，二是到什么山唱什么歌，出错机率会少点。

对聚合函数的讲解：
http://doc.javanb.com/hibernate-reference-3-2-0-zh/ch15s07.html