SQL Server查询来计算余额
问题描述:
我希望我的SQL查询可以像这样运行。SQL Server查询来计算余额
我有两个表:
:- 键1,迄今为止,在
- 键2,日期,出
直到现在我用UNION
实现这个
select Date , In , '' as 'out'
from table1
Union ALL
select Date, '' as In, Out
from table2
余额如何?
请帮我
答
目前,最快,实际上仅,方法来计算在SQL Server中运行总计是使用游标。
Declare @RunningTotals Table
(
PrimaryKeyCol int not null Primary Key
, TableName nvarchar(128) not null
, Total money not null Default (0)
)
Declare @Values Cursor
Declare @PrimaryKeyCol int
Declare @TableName nvarchar(128)
Declare @Date datetime
Declare @In money
Declare @Out money
Set @Values = Cursor Fast_Forward For
Select Key1, 'Table1' As TableName, Date , In , Null as out
From table1
Union All
Select Key2, 'Table2', Date, Null as In, Out
From Table2
Order By Date
Open @Values
Fetch Next From @Values Into @PrimaryKeyCol, @TableName, @In, @Out
Set @Total = 0
While @@Fetch_Status = 0
Begin
Set @Total = @Total + Coalesce(@In,0) - Coalesce(@Out,0)
Insert @RunningTotals(PrimaryKeyCol, TableName, Total)
Values(@PrimaryKeyCol, @TableName, @Total)
Fetch Next From @Values Into @PrimaryKeyCol, @TableName, @In, @Out
End
Close @Values
Deallocate @Values
Select Date, In, Out, RT.Total
From (
Select Key1 As PrimaryKeyCol, 'Table1' As TableName, Date , In , Null as out
From table1
Union All
Select Key2, 'Table2', Date, Null as In, Out
From Table2
) As Z
Join @RunningTotals As RT
On RT.PrimaryKeyCol = T.PrimaryKeyCol
And RT.TableName = Z.TableName
您的样本数据中的起始余额500是从哪里来的? – 2011-05-12 15:34:07
请参阅[在SqlServer中计算运行总数](http://*.com/questions/860966/calculate-a-running-total-in-sqlserver)了解有关各种方法的一些讨论。 – 2011-05-12 15:34:49
[Calculate running total/running balance]的可能重复(http://*.com/questions/11310877/calculate-running-total-running-balance) – 2015-07-27 13:03:35