HQL:基于属性值的最大/限制结果

时间:2011-02-22 12:17:04

标签: hibernate grails hql

我有一个域名AccountTransaction

class AccountTransaction {
  Account account
  BigDecimal amount
  ...
}

我想获得每个帐户最多3笔交易。 预期产出:

id  | account | amount
______________________
1   | a1      | 200
21  | a1      | 300
33  | a1      | 100
11  | a2      | 100
22  | a2      | 30
31  | a2      | 10
55  | a3      | 20

我应该如何编写HQL / Criteria查询?是否真的受到支持?

2 个答案:

答案 0 :(得分:1)

我创建了一些列日期,用于处理最新的交易

SQL:

select id, account, amount
from account_transaction as at1
where (
   select count(*) from account_transaction as at2
   where at1.account_id = at2.account_id and at1.date_created < at2.date_created
) <= 2;

HQL:

AccountTransaction.executeQuery("select id, account, amount from AccountTransaction as at1
where (select count(*) from AccountTransaction as at2 
where at1.account = at2.account and at1.date_created > at2.date_created) <= 2")

答案 1 :(得分:0)

我认为您不必使用HQL / Criteria来获取此信息:

AccountTransaction.list(max: 3, sort: 'amount', order: 'desc')