Retrieve value from the row above

Michael M.M. D'Angelo 176 Reputation points
2024-04-15T21:16:50.3333333+00:00

How can I retrieve the FinalBalance value from the previous row and add it to the Total value in the current row, to get the new FinalBalance value for each row? The table structure and desired outcome are shown in the image below. Each row's TransDate is unique.

The SQL code to create the table and insert values is:

CREATE TABLE [dbo].[DalyBalances](
[TransDate] [date] NOT NULL,
[Others] [float] NOT NULL,
[LoansDisbursed] [float] NOT NULL,
[RepaymentReceived] [float] NOT NULL,
[BookletSales] [float] NOT NULL,
[InterestPaidOut] [float] NOT NULL,
[Total] [float] NULL,
[FinalBalance] [float] NOT NULL
) ON [PRIMARY]
GO
INSERT [dbo].[DalyBalances] ([TransDate], [Others], [LoansDisbursed], [RepaymentReceived], [BookletSales], [InterestPaidOut], [Total], [FinalBalance]) VALUES (CAST(N'2024-01-01' AS Date), 20000, 0, 0, 0, 0, 20000, 2000)
GO
INSERT [dbo].[DalyBalances] ([TransDate], [Others], [LoansDisbursed], [RepaymentReceived], [BookletSales], [InterestPaidOut], [Total], [FinalBalance]) VALUES (CAST(N'2024-04-12' AS Date), 0, 0, 0, 0, 0, 0, 2000)
GO
INSERT [dbo].[DalyBalances] ([TransDate], [Others], [LoansDisbursed], [RepaymentReceived], [BookletSales], [InterestPaidOut], [Total], [FinalBalance]) VALUES (CAST(N'2024-04-14' AS Date), 0, 1200, 200, 0, 10, 1400, 3400)
GO
INSERT [dbo].[DalyBalances] ([TransDate], [Others], [LoansDisbursed], [RepaymentReceived], [BookletSales], [InterestPaidOut], [Total], [FinalBalance]) VALUES (CAST(N'2024-04-15' AS Date), 0, 400, 0, 300, 10, 700, 4100)
GO

User's image

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,747 questions
SQL Server Transact-SQL
SQL Server Transact-SQL
SQL Server: A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.Transact-SQL: A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
42 questions
{count} votes

1 answer

Sort by: Most helpful
  1. CosmogHong-MSFT 23,246 Reputation points Microsoft Vendor
    2024-04-16T01:53:17.4133333+00:00

    Hi @Michael M.M. D'Angelo

    To retrieve the FinalBalance value from the previous row, you could use the LAG() function.

    Try this:

    SELECT *,[Total] + LAG([FinalBalance],1,0)OVER(ORDER BY [TransDate]) AS New_FinalBalance
    FROM [DalyBalances]
    

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    0 comments No comments