2011-05-12 151 views
2

我希望我的SQL查詢可以像這樣運行。SQL Server查詢來計算餘額

enter image description here

我有兩個表:

  1. 鍵1,迄今爲止,在
  2. 鍵2,日期,出

直到現在我用UNION實現這個

select Date , In , '' as 'out' 
from table1 

Union ALL 

select Date, '' as In, Out 
from table2 

餘額如何?

請幫我

+2

您的樣本數據中的起始餘額500是從哪裏來的? – 2011-05-12 15:34:07

+2

請參閱[在SqlServer中計算運行總數](http://stackoverflow.com/questions/860966/calculate-a-running-total-in-sqlserver)瞭解有關各種方法的一些討論。 – 2011-05-12 15:34:49

+0

[Calculate running total/running balance]的可能重複(http://stackoverflow.com/questions/11310877/calculate-running-total-running-balance) – 2015-07-27 13:03:35

回答

3

目前,最快,實際上僅,方法來計算在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