开发者

SQL Server query to calculate balance

I want my SQL query can run like this.

SQL Server query to calculate balance

I have two tables开发者_C百科:

  1. Key1, Date, In
  2. 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜