SQL Server query to calculate balance
I want my SQL query can run like this.
I have two tables开发者_C百科:
- Key1, Date, In
- key2, Date, Out
Until now I achieved this with a UNION
:
select Date , In , '' as 'out'
from table1
Union ALL
select Date, '' as In, Out
from table2
How about the balance ?
Please help me
At the present time, the fastest and practically only, way to calculate running totals in SQL Server is to use a cursor.
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
精彩评论