我有一些表格可用来维护每日的收入和支出。关于该数据:
daily_income - daily_expense
)计算为closing_balance
我需要将收入添加为前一天的期末余额,例如
我需要这种类型的计算
((Today's_OpeningBalance + Income) - (Expense)) = ClosingBalance
这是我的示例数据:
create table #dailyrep
(
Sno int identity(1, 1),
date date,
ScanAmount decimal(18, 2),
PaidAmount decimal(18, 2)
)
insert into #dailyrep (date, ScanAmount, PaidAmount)
values ('2019-05-10', 1000, 500),
('2019-05-11', 2000, 1000),
('2019-05-12', 2000, 2500),
('2019-05-13', 3000, 2000),
('2019-05-14', 5000, 3000)
这是我的尝试:
select
*,
(lead(isnull(a.ClosingBalance, 0.00)) over (order by date desc)) OpeningBalance
from
(select
date, ScanAmount Income, PaidAmount Expense,
ScanAmount - PaidAmount ClosingBalance
from
#dailyrep) a
order by
date desc
这是我想要的输出:
<html>
<head>
</head>
<body>
<table border =1>
<tr>
<td>Date </td> <td> Income </td> <td>Exp</td> <td>CloBal </td><td>OpenBal</td> <tr>
<tr><tr><td>2019-05-14</td><td> 5000.00</td><td> 3000.00 </td><td>4000.00 </td><td>2000.00</td></tr>
<tr><td>2019-05-13</td><td> 3000.00</td><td> 2000.00 </td><td>2000.00 </td><td>1000.00</td></tr>
<tr><td>2019-05-12</td><td> 2000.00</td><td> 2500.00 </td><td>1000.00 </td><td>1500.00</td></tr>
<tr><td>2019-05-11</td><td> 2000.00</td><td> 1000.00 </td><td>1500.00 </td><td>500.00 </td></tr>
<tr><td>2019-05-10</td><td> 1000.00</td><td> 500.00 </td><td>500.00 </td><td>NULL </td></tr>
</table>
</body>
</html>
预先感谢
Ranjith S
答案 0 :(得分:0)
您想要一个累加的总和,而不是一个滞后。看起来像:
select dr.*,
sum(income - expense) over (order by date)
from dailyrep dr;
您的示例数据与您的问题无关,因此我更改了列名here。