0

I have the following table that has a list of transactions

ID  FromID   ToId      AMOUNT
1   1        2         10
2   1        3         10
4   1        4         10
5   3        2         3
6   4        2         2
7   4        2         1
8   2        4         2

I'd like to know the best/most effecient way to get a users balance. The balance would be the sum of the amount the user has been given (where ID is ToId) minus the sum of the amount the user has given out (where ID is FromId)

Any ideas?

Thanks in advance.

James

4

3 回答 3

6

用一个简单的总和

select SUM(Amount) from
(
select Amount from #t where ToID=@user
union all
select -Amount from #t where FromID=@user
) v

(您可以在一行中完成...

select sum(case @user when ToID then Amount else -Amount end) 
from #t where @user in (ToID, FromID)

但我认为工会会更有效率)

于 2012-07-19T14:35:15.880 回答
1

“最佳”方式是主观的。最有效的方法可能是在您的用户表中添加一个余额字段,然后在您有该用户的交易时适当地更新它。

[编辑]澄清:

在插入事务行的代码中,在事务内添加更新查询:

BEGIN TRANSACTION;
INSERT INTO transactions VALUES (...);
UPDATE users SET balance = balance + <whatever the change is>;
COMMIT TRANSACTION;

然后你的余额检查就变成了:

SELECT balance FROM users WHERE id = '...';

它是索引的,速度极快,并且只需要考虑一行。如果您依赖事务表的主动求和,那么您的余额检查查询将随着您添加事务而变慢。

于 2012-07-19T14:36:24.197 回答
0

将两组金额相加(SUM 给用户的所有金额以及 SUM 所有给出的金额)- 将两者相减(如果使用 SQL Server,您可以使用 (-) SUBTRACT)

于 2012-07-19T14:36:17.867 回答