2

我当前的 Account Balance 对象中有以下属性:

long id;                     // Database ID
Date date;                   // date when this balance object was created
boolean currentBalanceFlag;  // indicates this is the most recent balance
float amount;                // the total sum currently in the account balance
float depositAmount;         // amount deposited that resulted in this objects amount 
float withdrawalAmount;      // amount withdrawn that resulted in this objects amount
Balance lastBalance;         // last balance object for traversing
User user;                   // owner of the balance
String note;                 // detailed description of transaction that resulted in current blanace

天平上只执行了两个操作。存款和取款。

问题是:

如何创建 HQL 查询:

-sum all depositAmountfor user
-sum all withdrawalAmountfor user
-从第二个求和中减去第一个求和的
结果 -将减法结果与等于的amountfor userinBalance对象进行比较currentBalanceFlagtrue

在伪代码中:

resultAmount = select ( sum(depositAmount) - sum(withdrawalAmount) ) from Balance where user=user
amount = select amount from Balance where user=user and currentBalanceFlag=true

我想通过 HQL 查询从对数据库的单次调用中获得最终的布尔结果:

resultAmount == amount
4

1 回答 1

1
select (sum(flow.depositAmount) - sum(flow.withdrawalAmount) - current.amount) 
from Balance flow, Balance current
where flow.user=:user
and current.user=:user 
and current.currentBalanceFlag=true

这将返回所有流量的总和与当前余额之间的差值。

附带说明一下,您不必检查数据的完整性。除非您有数以亿计的行,否则使用 SQL 总和计算当前余额应该足够快。

于 2011-01-30T10:42:18.860 回答