简体   繁体   中英

greatest-n-per-group in hibernate

Is there any way in hibernate to get greatest record from a group. In my table I have three columns(error_id, transaction_id, phone) I want to apply order by clause on transaction_id and then make group on basis of phone and then want to get top record from each group.

Any suggestions for this type or query.... Thanx in Advance.

I got the answer from my search.

String msisdnQueryString = "SELECT DISTINCT table.phone FROM TABLE_NAME table";
Query msisdnQueryObject = session.createQuery(msisdnQueryString);
List msisdnList = msisdnQueryObject.list();

List<Long> transactionList = new ArrayList<Long>();
for(Object object : msisdnList){
    Long msisdn = Long.parseLong(object.toString());
    String transactionQueryString = "SELECT table.transactionId FROM TABLE_NAME table WHERE table.phone = "+msisdn+" ORDER BY table.transactionId DESC";
    Query transactionQueryObject = session.createQuery(transactionQueryString);
    transactionQueryObject.setFirstResult(0);
    transactionQueryObject.setMaxResults(1);
    List transactions =transactionQueryObject.list();
    if(transactions.size() > 0){
    transactionList.add((Long)transactions.get(0));
    }
}

It is a long process but it is working. If any one know better way to get such records then please post your answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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