SQL Server查询以计算余额
我希望我的SQL查询可以这样运行 我有两张桌子:SQL Server查询以计算余额,sql,sql-server,Sql,Sql Server,我希望我的SQL查询可以这样运行 我有两张桌子: 键1,日期,输入 键2,日期,输出 到目前为止,我是通过一个联合体来实现这一点的: select Date , In , '' as 'out' from table1 Union ALL select Date, '' as In, Out from table2 余额呢 请帮助我目前,在SQL Server中计算运行总数的最快也是最实用的方法是使用光标 Declare @RunningTotals Table (
联合体来实现这一点的:
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的起始余额来自何处?有关各种方法的讨论,请参阅。可能重复的