SQL查询以计算每个记录中先前记录的总和

时间:2019-03-04 15:22:55

标签: sql sql-server

enter image description here

我想在每行中获取等于(所有先前previous balance的总和-(所有先前debit的总和))的计算字段(credit

例如:

对于ID = 5,我想获得该记录的先前余额=(借方金额之和)-(贷方金额之和)从ID = 1到ID = 4

有什么建议吗? 我尝试了LAG函数,但仍然没有得到我想要的 谢谢

1 个答案:

答案 0 :(得分:0)

您好,如果我了解您的查询墙,并且您的SQL Server版本大于或等于2008,则可以使用以下查询示例::

Create table #tblVal
(
Id int identity(1,1),
Val int
)
--Inserting Records--
Insert into #tblVal values(720)
Insert into #tblVal values(720)
Insert into #tblVal values(500)
Insert into #tblVal values(720)
Insert into #tblVal values(539)
Insert into #tblVal values(341)



select * from #tblVal

SELECT *, SUM(Val) OVER(ORDER BY Id Asc
     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) - Val as 'TotalSumPrevious',
     SUM(Val) OVER(ORDER BY Id Asc
     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as 'TotalSumCurrent'
FROM #tblVal 

drop table #tblVal 

并查看此链接:https://docs.microsoft.com/en-us/sql/t-sql/queries/select-over-clause-transact-sql?view=sql-server-2017

使用示例图片进行代码编辑:

Create table #tblVal
(
Id int identity(1,1),
Debit int,
Credit int
)
--Inserting Records--
Insert into #tblVal values(10,0)
Insert into #tblVal values(0,5)
Insert into #tblVal values(20,0)
Insert into #tblVal values(0,30)
Insert into #tblVal values(10,0)
Insert into #tblVal values(0,30)
Insert into #tblVal values(10,0)



select * from #tblVal

SELECT *, 
     SUM(Debit - Credit)  OVER(ORDER BY Id Asc
     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) - (Debit - Credit) as 'PreviousBalance'
FROM #tblVal 

drop table #tblVal