Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL Server查询以计算余额_Sql_Sql Server - Fatal编程技术网

SQL Server查询以计算余额

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 (

我希望我的SQL查询可以这样运行

我有两张桌子:

  • 键1,日期,输入
  • 键2,日期,输出
  • 到目前为止,我是通过一个
    联合体来实现这一点的:

    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的起始余额来自何处?有关各种方法的讨论,请参阅。可能重复的