HQL中的MAX FROM COUNT

时间:2012-04-18 14:14:40

标签: count hql max

我有医生和患者课程,每个医生都有一些患者(1:m)。 如何找到HQL中患者最多的医生(或医生)?

这里是SQL查询:

SELECT D.doctorName, count(D.patientId) AS tot FROM Doctors AS D GROUP BY D.doctorName HAVING count(D.patientId)= (SELECT max(A.pid) FROM( SELECT count(D.patientId) AS pid FROM Doctors AS D GROUP BY D.doctorName) AS A)

主要问题是我无法在FROM位置编写子查询。

非常感谢。

[R

2 个答案:

答案 0 :(得分:1)

解决!我已经创建了一个CRITERIA函数来替换子查询。不优雅,但有效!

    def myList = []
    String tempName = ""
    int patPosition = 0
    int myListPosition = -1
    int find = 0
    int maxOcc = 0

    def c = Doctor.createCriteria()
    def pat = c.list {              
        patients {          
        }
    }

    while(patPosition<pat.size()){

        find=0
        tempName=pat[patPosition].lastName //Some constraints to add 
        find=pat.lastName.count(tempName)

        if(find>maxOcc){
            maxOcc=find
        }

        myListPosition=myListPosition+1
        myList[myListPosition]=find

        patPosition=patPosition+find

    }

    print "\n\nLIST -> "+myList
    print "MAX -> "+maxOcc

    String queryToDo=   "SELECT d.name, count(p) "+
                        "FROM Doctor as d INNER JOIN d.patients as p "+
                        "GROUP BY d.name "+
                        "HAVING count(p) = $maxOcc" 

    def query = Doctor.executeQuery(queryToDo)  
    render query

答案 1 :(得分:0)

更多合成:

pat.eachWithIndex{item, index-> 
          if (index.equals(index2)){
            patCount=0
            patCount=pat.count(item)    
            index2=index2+patCount
                if(patCount>maxOcc){
                    maxOcc=patCount
                }
          } 
     }