# mssql sqlerver 脚本 计算数据表的结余数的方法分享

```detail表 记帐流水表
==========

qt_srMoney   (money) 收入
qt_zcMoney  (money) 支出
qt_date         (datetime) 操作日期
qt_dkfs         (nvarchar)  打款方式
------------------

==========

*/
create table detail(qt_srMoney   money,
qt_zcMoney  money,
qt_date         datetime,
qt_dkfs         nvarchar(100))
insert into detail values(100,0,‘2018-1-2 10:00:00‘,‘other‘)
insert into detail values(0,10,‘2018-2-2 10:00:00‘,‘other‘)
insert into detail values(0,20,‘2018-3-2 10:00:00‘,‘other‘)
insert into detail values(30,0,‘2018-4-2 10:00:00‘,‘other‘)
insert into detail values(10,60,‘2018-5-2 10:00:00‘,‘other‘)
go

declare @datestart datetime ---开始计算日期
set @datestart =‘2018-2-1‘
declare @qcomney money --期初
set @qcomney =100

select t1.qt_date,t1.qt_dkfs,t1.qt_srMoney,t1.qt_zcMoney,sum(t2.qt_srMoney-t2.qt_zcMoney)+@qcomney
from detail t1,detail t2
where t1.qt_date>=t2.qt_date
and t1.qt_date >=@datestart
group by t1.qt_date,t1.qt_dkfs,t1.qt_srMoney,t1.qt_zcMoney
order by t1.qt_date;
go

---避免日期出现两条导致结余数据计算异常-----
declare @datestart datetime ---开始计算日期
set @datestart =‘2018-2-1‘
declare @qcomney money --期初
set @qcomney =100

with cteName  as
(
select qt_srMoney,qt_zcMoney,qt_date,qt_dkfs,
row_number() over ( order by qt_date)  as keyID  from detail where qt_date >=@datestart
)  select t1.keyId,t1.qt_date,t1.qt_dkfs,t1.qt_srMoney,t1.qt_zcMoney,sum(t2.qt_srMoney-t2.qt_zcMoney)+@qcomney
from cteName t1,cteName t2
where t1.keyId>=t2.keyId
group by t1.qt_date,t1.qt_dkfs,t1.qt_srMoney,t1.qt_zcMoney,t1.keyId
order by t1.keyId;

go
truncate table detail
drop table detail```

mssql sqlerver 脚本 计算数据表的结余数的方法分享

(0)
(0)