我想在每行中获取等于(所有先前previous balance
的总和-(所有先前debit
的总和))的计算字段(credit
>
例如:
对于ID = 5,我想获得该记录的先前余额=(借方金额之和)-(贷方金额之和)从ID = 1到ID = 4
有什么建议吗?
我尝试了LAG
函数,但仍然没有得到我想要的
谢谢
答案 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
使用示例图片进行代码编辑:
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