我仍然遇到计算运行平衡的最佳方法的问题。
我将在我将要在SSRS中生成的Rent Statement中使用此代码,但我遇到的问题是我似乎无法弄清楚如何实现运行平衡。
SELECT rt.TransactionId,
rt.TransactionDate,
rt.PostingDate,
rt.AccountId,
rt.TotalValue,
rab.ClosingBalance,
ROW_NUMBER()OVER(PARTITION BY rt.AccountId ORDER BY rt.PostingDate desc) AS row,
CASE WHEN ROW_NUMBER()OVER(PARTITION BY rt.AccountId ORDER BY rt.PostingDate desc) = 1
THEN ISNULL(rab.ClosingBalance,0)
ELSE 0 end
FROM RentTransactions rt
--all accounts for the specific agreement
INNER JOIN (select raa.AccountId
from RentAgreementEpisode rae
inner join RentAgreementAccount raa on raa.AgreementEpisodeId = rae.AgreementEpisodeId
where rae.AgreementId=1981
) ij on ij.AccountId = rt.AccountId
LEFT JOIN RentBalance rab on rab.AccountId = rt.AccountId AND rt.PostingDate BETWEEN rab.BalanceFromDate AND isnull(rab.BalanceToDate,dateadd(day, datediff(day, 0, GETDATE()), 0))
这给我的是以下结果 - 我已将结果包括在内 -
所以我的代码按照我想要的顺序对事务进行排序,并且也按照正确的顺序对它们进行行编号。
行号为1 - 我需要它在那个时间点撤回该帐户的余额,这正是我正在做的......但是我不确定如何让我的代码启动减去前一行 - 所以在这种情况下,1118.58的当前数字需要从第2行减去91.65的总值 - 因此第2行的运行余额将是1026.93,依此类推......
非常感谢任何帮助。
答案 0 :(得分:1)
假设您在查询中返回了所有事务,您可以使用over
子句计算运行总计,您只需从数据集的开头开始,而不是从当前余额向后工作:< / p>
declare @t table(d date,v decimal(10,2));
insert into @t values ('20170101',10),('20170102',20),('20170103',30),('20170104',40),('20170105',50),('20170106',60),('20170107',70),('20170108',80),('20170109',90);
select *
,sum(v) over (order by d
rows between unbounded preceding
and current row
) as RunningTotal
from @t
order by d desc
输出:
+------------+-------+--------------+
| d | v | RunningTotal |
+------------+-------+--------------+
| 2017-01-09 | 90.00 | 450.00 |
| 2017-01-08 | 80.00 | 360.00 |
| 2017-01-07 | 70.00 | 280.00 |
| 2017-01-06 | 60.00 | 210.00 |
| 2017-01-05 | 50.00 | 150.00 |
| 2017-01-04 | 40.00 | 100.00 |
| 2017-01-03 | 30.00 | 60.00 |
| 2017-01-02 | 20.00 | 30.00 |
| 2017-01-01 | 10.00 | 10.00 |
+------------+-------+--------------+