【问题标题】:HQL : max/limit result based on property valueHQL:基于属性值的最大/限制结果
【发布时间】:2011-02-22 12:17:03
【问题描述】:

我有一个域,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 查询?真的支持吗?

【问题讨论】:

    标签: hibernate grails hql


    【解决方案1】:

    我创建了一些列 date_created 来处理最新的交易

    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")
    

    【讨论】:

    • 感谢一百万!它刚刚奏效。只是使用 id 而不是 dateCreated 即 at1.id
    【解决方案2】:

    我认为你不必使用 HQL/Criteria 来获得这个:

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

    【讨论】:

    • 这将给出三个金额最高的条目。但他会列出每个账户金额最高的三个条目。
    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    相关资源
    最近更新 更多