gpt4 book ai didi

用于计算余额的 SQL Server 查询

转载 作者:行者123 更新时间:2023-12-04 06:26:35 35 4
gpt4 key购买 nike

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

enter image description here

我有两个表:

  • Key1,日期,在
  • key2,日期,出

  • 到目前为止,我是通过 UNION 实现的。 :
    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

    关于用于计算余额的 SQL Server 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5980495/

    35 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com